0
>>> x = [1,2,3]
>>> y = [1,2,3]
>>> print id(x),id(y)
43259384 43258744

>>> x = 1
>>> y = 1
>>> print id(x),id(y)
5417464 5417464

As you can see the IDs are different for the first print but the same for the second print. Why? What determines whether or not the IDs of 2 variables will be the same after they have been assigned the same value?

JamesGold
  • 795
  • 2
  • 8
  • 24
  • @IgnacioVazquez-Abrams This question regards lists, which should not have the same `id`. The whole content of this question is not explained by the link – jamylak Jun 16 '13 at 04:00
  • 2
    Numbers are immutable. Because of this, Python implementations *may* utilize Interning (as described in the answers in the Related post) - Java does the same thing for a limited set of Integers. Other language implementations (i.e. ELisp and MRI Ruby) use "immediate values" as another optimization which has the same result when comparing identities. – user2246674 Jun 16 '13 at 04:00
  • @jamylak the lists do not have the same id. – andrew cooke Jun 16 '13 at 04:01
  • @user2246674 just post that as an answer instead of comment ;) – jamylak Jun 16 '13 at 04:02

2 Answers2

0

The small integers are getting interned.

Short ints with small values (typically between -1 and 99 inclusive) are "interned" -- whenever a result has such a value, an existing short int with the same value is returned. This is not done for long ints with the same values.

Further,

But code may exist that uses 'is' for comparisons of short ints and happens to work because of this interning. Such code may fail if used with long ints.)

However, this isn't behavior that should be relied upon as it is implementation-specific. It isn't going to work for larger integers and interning isn't guaranteed, so you shouldn't be using is here. Other than integers, strings may also be interned.

(PEP-0237)

Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
0

As @jamylak points out, your first test compares the id of two lists, not the integers they contain. If you actually compare the integers in the lists -- for example print id(x[0]), id(y[0]) -- you may get the same id.

>>> x = [1, 2, 3]
>>> y = [1, 2, 3]
>>> print id(x[0]), id(y[0])
4298179016 4298179016
Justin S Barrett
  • 636
  • 4
  • 14
  • 1
    This is true due to interning as shown in the link by @Ignacio but I was more so emphasizing the fact that list are mutable. – jamylak Jun 16 '13 at 04:08