Variables are references to objects. a
does not reference the same object as b
. Even though the two objects are the same they have unique addresses in memory and do not depend on each other.
>>> a = b = [1,2,3]
>>> c = [1,2,3]
>>> print(a is b)
True
>>> print(a is c or b is c)
False
>>> a.remove(1)
>>> print(a)
[2, 3]
>>> print(b)
[2, 3]
>>> print(c)
[1, 2, 3]
In the case of the x = 2
and id(x) == id(2)
integers are immutable and in CPython id
is simply the location of an object in memory. Integers are always the same so storing the same integer several times at different addresses would be a waste of memory.
However, in general DO NOT use integers with is
operator as it can lead to different results across different python implementations.