0

First of all I know this is not a great question, but I am starting out at Python and trying to understand the mechanics of things along. The following code is the output from a Python 3.4 interpreter:

>>> a = 9
>>> b = a
>>> a is b
True
>>> b is a
True
>>> hex(id(a))
'0x9a34e0'
>>> hex(id(b))
'0x9a34e0'

Now I understand the above part, but when i assign b = 9:

>>> b = 9
>>> a is b
True
>>> b is a 
True
>>> hex(id(a))
'0x9a34e0'
>>> hex(id(b))
'0x9a34e0'

I don't understand: why is b still the same object as a? Why isn't a newly freshly made object assigned to it? If we look for a parallel situation in case of lists this doesn't happen:

>>> x = [1, 2, 3]
>>> y = x
>>> x is y
True
>>> y is x
True
>>> hex(id(x))
'0x7fc588004e48'
>>> hex(id(y))
'0x7fc588004e48'
>>> y = [1, 2, 3]
>>> x is y
False
>>> y is x
False
>>> hex(id(x))
'0x7fc588004e48'
>>> hex(id(y))
'0x7fc588009a48'

Why are ints variables still considered the same even after reassignment? In lists, though, I assigned the same list but a new object was made, which I understand.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
user_3068807
  • 397
  • 3
  • 13
  • Now try with `12345678901234567890` instead of `9`... – tobias_k Nov 30 '15 at 10:38
  • @tobias_k yes if the integer is different then it is fine. But in lists as well i am providing the same list but a new object is assigned. – user_3068807 Nov 30 '15 at 10:40
  • 6
    For efficiency, the CPython interpreter "recycles" small integers in the range -5 to 256. See [Python's “is” operator behaves unexpectedly with integers](http://stackoverflow.com/q/306313/4014959) – PM 2Ring Nov 30 '15 at 10:41

1 Answers1

1

In the first example, Python isn't assigning to b the same ID because you're assigning a to it, but because you are assigning 9 to it.

Small integers (from -5 to 256) in Python are cached to make mathematical operations faster. Therefore every variable that has the same small integer value also refers to the same memory address, and has the same ID. In fact, you could do id(9) and see that it's equal to id(a).

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128