Unexpected Behavior of "is" Operator with Integers
The "is" operator in Python compares object identity, testing if two variables refer to the same exact object in memory. However, it can behave unexpectedly when comparing integers.
Consider the following example in Python 2.5.2:
>>> a = 256 >>> b = 256 >>> a is b True # Expected result >>> a = 257 >>> b = 257 >>> a is b False # Unexpected result
Why does the "is" operator return False when comparing integers 257?
The answer lies in the way Python internally represents small integers. According to the Python documentation, integers between -5 and 256 are stored in a preallocated array. When you create an integer in this range, you actually get a reference to the corresponding array element.
This means that for integers between -5 and 256, the "is" operator is essentially comparing memory addresses instead of integer values. In the example above, a and b are both referencing the same element in the array, hence the True result.
However, for integers outside this range, the "is" operator behaves as expected. It compares the actual integer values, not the memory addresses.
If you need to compare two objects of unknown type, regardless of whether they are integers or not, you can use the "id()" function to obtain their memory addresses and compare those instead:
>>> a = 257 >>> b = 257 >>> id(a) == id(b) False
The above is the detailed content of Why Does Python's 'is' Operator Behave Unexpectedly with Certain Integers?. For more information, please follow other related articles on the PHP Chinese website!