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 == ?

Community
  • 1
  • 1
jb.
  • 9,921
  • 12
  • 54
  • 90
  • 2
    See [this question](http://stackoverflow.com/questions/1504717/python-vs-is-comparing-strings-is-fails-sometimes-why) for an explanation of `is` vs `==` – brc Oct 10 '11 at 21:19
  • 1
    Lots of great links. The only time you naively want to use `is` is for testing None. Otherwise default to `==` – chmullig Oct 10 '11 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. – Russell Borogove Oct 10 '11 at 23:08
  • 1
    @RussellBorogove I saw it on a comment on some SO question I was reading a couple days ago. – jb. Oct 10 '11 at 23:49

2 Answers2

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
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 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 Oct 10 '11 at 21:23
  • 2
    @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. – Mark Byers Oct 10 '11 at 21:26
  • 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. – David Heffernan Oct 10 '11 at 21:33
  • @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`. – agf Oct 11 '11 at 06:53
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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490