Possible Duplicate:
Python “is” operator behaves unexpectedly with integers
I’m learning Python, and am curious as to why:
x = 500
x is 500
returns False, but:
y = 100
y is 100
returns True?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Python reuses small integers. That is, all
1s (for example) are the same1object. The range is -5 to 255, if I remember correctly, though this is a CPython implementation detail that should not be relied upon. I am pretty sure Jython and IronPython, for example, handle this differently.The reason this works out fine is that
ints are immutable. That is, you can’t change a4to a5in-place. ifahas a value of 4,a = 5is actually pointingato a different object, not changing the valueacontains. Python doesn’t share any mutable types (such as lists) where unexpectedly having multiple references to the same object might cause problems.You should use
==for comparing most things.isis for checking to see whether two references point to the same object; it is roughly equivalent toid(x) == id(y).