Possible Duplicate:
Python “is” operator behaves unexpectedly with integers
Why (0-6) is -6 = False?
So, while playing with a bit with id (python 2.6.5), I noticed the following (shell session):
>>> a = 1
>>> id(a)
140524904
>>> b = 1
>>> id(b)
140524904
Of course, as soon as I modify one of the variables it gets assigned to a new memory address, i.e.
>>> b += 1
>>> id(b)
140524892
Is it the normal behavior to initially assign both variables that have identical values to the same memory location or just an optimization of i.e. CPython?
P.s. I spent a little time browsing around the code in parser, but couldn’t find where and how variables are allocated.
As mentioned by glglgl, this is an implementation detail of CPython. If you look at
Objects/longobject.cin the source code for CPython (e.g. version 3.3.0), you’ll find the answer to what’s happening:This explains why, after
a = 1; b = 1,a is bwill beTrue, even when you saya += 2; b +=2; a -= 2; b -= 2. Whenever a number is calculated to have a value that fits in this array, the resulting object is simply picked from this array instead, saving a bit of memory.You can figure out the bounds of this
small_intsarray using a function like this:For my build (Python 2.7, 64-bit Windows build),
small_int_bounds() == (-5, 256). This means that numbers between-5and256(inclusive) are shared through thesmall_intsarray inObjects/longobject.c.-edit- I see elssar noted that there is a similar answer about interning of some literals. This fact is also mentioned in the documentation for
PyInt_FromLong, as mentioned by this answer.