Given Python's distinction between object identity and equality, it might come as a surprise to find that:
>>> a = 256
>>> b = 256
>>> a is b
True
This happens because Python keeps a cache of commonly-used, small integer objects (on my system, -5
– 256
). To improve performance, the assignment a = 256
attaches the variable name a
to the existing integer object without having to allocate new memory for it. Since the same thing happens with b
, the two variables in this case do, in fact, point to the same object. By contrast,
>>> a = 257
>>> b = 257
>>> a is b
False