Reputation: 59303
Python seems to have a so called "small number cache" for numbers in the range -5 to 256. We can demonstrate that with the following program:
for i in range(-7, 258):
if id(i) == id(i + 0):
print(i, "is cached")
else:
print(i, "is not cached")
The output is
-7 is not cached
-6 is not cached
-5 is cached
-4 is cached
[...]
255 is cached
256 is cached
257 is not cached
I wonder whether that's defined in the Python specification or it's an implementation detail.
Upvotes: 4
Views: 108
Reputation: 59303
It's an implementation detail: chapter 3.1 of the Python language reference (all versions, from 2.7 through 3.9) says:
for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value
and
E.g., after
a = 1; b = 1
,a
andb
may or may not refer to the same object with the value one, depending on the implementation
(emphasis mine)
The Python/C API reference also mentions it
The current implementation keeps an array of integer objects for all integers between -5 and 256,
(emphasis mine) which is also quite clear that this might change in the future.
Upvotes: 4