Why does the following behave in an unexpected manner in Python?
>>> a = 258
>>> b = 258
>>> a is b
True # This is an expected result
>>> a = 259
>>> b = 259
>>> a is b
False # What happened here? Why is this False?
>>> 258 is 258
True # Yet the literal numbers compare properly
Python 2.5.2 is what I’m using. Testing various Python versions, it appears that Python 2.3.3 exhibits the above behaviour between 99 and 100.
Based on the foregoing, I assume that Python is internally designed in such a way that “small” integers are stored differently than larger integers, and the is operator, like this [link removed by moderator] can discern the difference. Why the dripping abstraction? What is a better approach to compare two random things to see whether they are the same when I don’t know if they are numbers or not?
When I want to do a comparison, I use if a == b: or if a != b, depending on what the action for the following code will be.
Also, you’ll find (as likely as not) that you’ll get different results if you code what you have found, into a script and run said from a IDE, rather than directly from the REPL environment.
>>> a = 259
>>> b = 259
>>> a is b
False
>>> a == b
True
>>>
Just to make sure: you’re aware that Python 2.5.2 was released in February of 2008 (before Windows XP Service Pack 3, as a point of reference), and all support for 2.5 (including security fixes) ended a decade ago? That the current version is 3.11.3, and that 3.12 is in active development?
That said, this issue is found in all versions, and is commonly asked about. The short version is that using is to compare integers is pointless nonsense.