3

Possible Duplicate:
String comparison in Python: is vs. ==
When is the == operator not equivalent to the is operator? (Python)

I'm pretty new to Python still. I heard someone say use is, not == because "this isn't C". But I had some code x is 5 and it was not working as expected.

So, following proper Python/PEP style, when is the time to use is and when is the time to use == ?

4
  • 2
    See this question for an explanation of is vs == Commented Oct 10, 2011 at 21:19
  • 1
    Lots of great links. The only time you naively want to use is is for testing None. Otherwise default to == Commented Oct 10, 2011 at 21:22
  • 1
    Whoever you heard saying "use is, not ==" is flat wrong and you should take any other advice they give with a grain of salt. You almost never need to use is in Python. Commented Oct 10, 2011 at 23:08
  • 1
    @RussellBorogove I saw it on a comment on some SO question I was reading a couple days ago. Commented Oct 10, 2011 at 23:49

2 Answers 2

11

You should use == to compare two values. You should use is to see if two names are bound to the same object.

You should almost never use x is 5 because depending on the implementation small integers might be interned. This can lead to surprising results:

>>> x = 256
>>> x is 256
True
>>> x = 257
>>> x is 257
False
Sign up to request clarification or add additional context in comments.

4 Comments

When I do the second assignment and second is check, it still returns True. I'm using Python 2.7. EDIT: Actually, I used 1 and 2 for the first/second values, but then tried 256/257 and got the same results you listed. What's going on here?
@Manny D: In the Python implementation you are using, numbers that are 256 or less are interned for efficiency. Every time you write 256 you get the exact same object. Each time you write 257, you get a new, different object but with the same value of course. But you shouldn't rely on this behaviour because it may change in future versions.
Perhaps a better example would be two more different objects that compared as equal values. Say 1 and 1.0. This example is a bit esoteric when there are more obvious mainstream ones at hand.
@MannyD You can also get this odd behavior with short strings, as they can be interned as well. You'll also get it with singletons like True, False, and None.
2

The two operators have different meaning.

  • is tests object identity. Do the two operands refer to the same object?
  • == tests equality of value. Do the two operands have the same value?

When it comes to comparing x and 5 you invariably are interested in the value rather than the object holding the value.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.