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 int
s variables still considered the same even after reassignment? In list
s, though, I assigned the same list
but a new object was made, which I understand.