I tried the following code and It gave me different output.
>>> foo1 = 4
>>> foo2 = 2+2
>>> id(foo1)
37740064L
>>> id(foo
That is because the result of id
in numeric constants is implementation defined.
In your case, Python 2.7.2, IIRC, the issue is that the compiler builds a few useful integer constants as singletons, (from -1 to 100 or so). The rationale is that these numbers are used so frequently that it makes no sense to dynamically allocate them each time they are needed, they are simply reused.
But that constant singleton optimization is not useful for float
values, other than maybe 0.0, there are too many of them! So each time a new float
value is needed it is allocated, and it gets a different id.
For a more deeply insight, read the source! This file is from Python3, but the idea is the same: look for the small_ints
array.