私は最近いじっていてid、(c?)Python が非常に賢明なことをしていることに気付きました: 小さな int が常に同じid.
>>> a, b, c, d, e = 1, 2, 3, 4, 5
>>> f, g, h, i, j = 1, 2, 3, 4, 5
>>> [id(x) == id(y) for x, y in zip([a, b, c, d, e], [f, g, h, i, j])]
[True, True, True, True, True]
しかし、数学的演算の結果についても同じことが言えるのではないかと思いました。それは次のとおりです。
>>> nines = [(x + y, 9) for x, y in enumerate(reversed(range(10)))]
>>> [id(x) == id(y) for x, y in nines]
[True, True, True, True, True, True, True, True, True, True]
n=257 で失敗し始めるようです...
>>> a, b = 200 + 56, 256
>>> id(a) == id(b)
True
>>> a, b = 200 + 57, 257
>>> id(a) == id(b)
False
しかし、より大きな数でも機能する場合があります。
>>> [id(2 * x + y) == id(300 + x) for x, y in enumerate(reversed(range(301)))][:10]
[True, True, True, True, True, True, True, True, True, True]
何が起きてる?Pythonはこれをどのように行いますか?