Python Integer Caching

In the following python script, why does the second statement pass (i.e. when adding 0 to 257 and save the result in y, then x and y become different objects)? Thank!

x = 257
y = 257
assert x is y

x = 257            
y = 257 + 0
assert x is not y
+4
source share
2 answers

integers are not changed, so any operation to change them leads to the creation of a new memory cell

>>> a =9876
>>> id(a)
38478552
>>> a+=1
>>> id(a)
38478576
>>> a+=0
>>> id(a)
38478528

is checks the actual location of the object’s memory ... and in principle, it will never be used to verify the equality of values ​​(although it can arbitrarily work on a small subset of cases)

+1
source

is, , . , True. False.

, ==, . assert x == y. , , , !=, . assert x != y.

x = 257
y = 257


>>> id(x)
4576991320

>>> id(y)
4542900688

>>> x is y
False

x = 257
y = 257 + 0

>>> id(x)
4576991368

>>> id(y)
4576991536
+1

All Articles