I came across a very odd behavior that I can't quite explain (running Python 2.7.6).
It is common knowledge that you shouldn't compare strings using is
in Python. However, I was completely unaware that similar badness can happen trying to compare int
s.
Take the following script for example:
for x, y in zip(xrange(0,399), xrange(1,400)):
z = y - 1
if x is z:
res = 'good'
else:
res = 'bad '
print res, x, z
Output:
...
good 254 254
good 255 255
good 256 256
bad 257 257
bad 258 258
bad 259 259
...
At this seemingly magic value of 257
, is
stops working as expected. For some reason, Python makes a new container to hold the calculation result.
However, it only seems to be when a calculation is involved, and the value is greater than 256
:
>>> 255 is 255
True
>>> 256 is 255 + 1
True
>>> 257 is 257
True
>>> 258 is 257 + 1
False
What is so special about 257
? Have I been mislead this entire time and shouldn't be using is
to compare int
s?