2

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?

aldeb
  • 6,588
  • 5
  • 25
  • 48
Sharp3
  • 108
  • 4
  • 1
    related : http://stackoverflow.com/questions/11476190/why-0-6-is-6-false – Ashwini Chaudhary Apr 24 '13 at 17:44
  • @AshwiniChaudhary: You may want to summarize and post as an answer since that answers the question. – Guvante Apr 24 '13 at 17:44
  • See also: http://stackoverflow.com/questions/306313/python-is-operator-behaves-unexpectedly-with-integers – Mark Hildreth Apr 24 '13 at 17:46
  • 2
    @Guvante: why would he do that? Voting to close as duplicate is the correct course of action. No need to rephrase existing answers from another question here. – Wooble Apr 24 '13 at 17:51
  • @Wooble: Because while the answer is the same, I could not tell if the question was the same. I don't recognize `id` versus `is` so didn't want to claim duplicate. – Guvante Apr 24 '13 at 20:54

2 Answers2

5

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
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
3

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343