2

Possible Duplicate:
Python β€œis” operator behaves unexpectedly with integers

in python 2.6.6 when I use int() to convert a string to a number the below code doesn't behave correct if the string is 257 or larger.

curr = int("256")  
myint = int("256")  
if curr is myint:  
    print("true")  
else:  
    print("false")  

this returns true which is correct

curr = int("257")  
myint = int("257")  
if curr is myint:  
    print("true")  
else:  
    print("false")  

this returns false ???

Community
  • 1
  • 1

3 Answers3

6

You should not use is to compare integers. Use == instead.

is should only be used to test if two variables are pointing to the same object. In Python, small numbers are interred and you often get the same object for the same int literal, but not always and not for larger numbers.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Exactly right. Example: >>> int("256") is int("256") True >>> int("257") is int("257") False >>> int("257") == int("257") True – Renklauf Nov 06 '12 at 18:11
4

That's because all integers from -5 to 256 are cached, so you're going to get is as True for them.

Read Python integer objects implementation

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

You should use == operator to compare integers, and use is when comparing to None or same objects.

>>> a = 257
>>> b = 257
>>> a is b
False
>>> a == b
True
Andrey Kuzmin
  • 4,479
  • 2
  • 23
  • 28