Unexpected Behavior of "is" Operator with Integers
Python's "is" operator is used to compare the identity of two objects. In the given code, the following behavior seems unexpected:
>>> a = 256 >>> b = 256 >>> a is b True # Expected result >>> a = 257 >>> b = 257 >>> a is b False # This is surprising, despite both values being equal.
To understand this behavior, we need to consider Python's implementation of integers. For small integers (specifically, those between -5 and 256), Python stores them as immutable objects. When multiple variables reference such a small integer, they all point to the same underlying object.
This explains the first comparison, where both a and b are references to the same object, hence is b returns True. However, for integers greater than 256, Python treats them as new objects, so a = 257 and b = 257 create separate objects, and a is b correctly returns False.
To avoid relying on this implementation detail, it's better to compare two arbitrary objects using ==, the equality operator, which checks the object's value for equality, regardless of its identity.
The above is the detailed content of Why Does Python's 'is' Operator Behave Unexpectedly with Integers?. For more information, please follow other related articles on the PHP Chinese website!