Question

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?

Was it helpful?

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

OTHER TIPS

There are 2 things going on here:

  • Small Python integers (from -5 to 256 inclusive) are interned; a literal integer is translated into the exact same object for the same number. For these integers their id() is going to be constant.

  • The id() is only unique for the lifetime of the object; it can be reused later on for another object if the first object has been cleared again. You don't store your literals anywhere, so the memory address can be reused again:

    >>> id('foo bar')
    4572936304
    >>> id('bar baz')
    4572936304
    

    Here 'foo bar' and 'bar baz' are two distinct objects, but their lifetimes do not overlap. The first is created, passed to the id() function, then destroyed again. Then the second string is created, passed to id() and destroyed in turn.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top