pythonliteralsname-binding

Why and how does the Python interpreter remember literal objects


I am surprised by the following result, using Python 2.7.4:

>>> id(5)
5068376

>>> id(5)
5068376

When the expression 5 is evaluated, a new object is created with the identity of 5068376. Now, I would expect that repeating the same statement would create another new object, whose identity would be unique, since simply evaluating an expression doesn't yield any references to the object and the object should be garbage collected.

It's not that the interpreter is reusing the same memory address either:

>>> id(6)
5068364

>>> id(5)
5068376

So what gives? Does the interpreter do behind-the-scenes binding of literals?


Solution

  • There's a range of small numbers that are kept as singletons within Python; any reference will always return the same object and they will never be garbage collected.

    >>> for x,y in enumerate(range(1000)):
        if x is not y:
            print x,y
            break
    
    257 257