6

Possible Duplicate:
Python ‘==’ vs ‘is’ comparing strings, ‘is’ fails sometimes, why?

In Python, what is the difference between these two statements:

if x is "odp":

if x == "odp":

codeforester
  • 39,467
  • 16
  • 112
  • 140
Nick Heiner
  • 119,074
  • 188
  • 476
  • 699
  • 3
    dupe http://stackoverflow.com/questions/1504717/python-vs-is-comparing-strings-is-fails-sometimes-why – SilentGhost Mar 10 '10 at 18:11
  • 1
    @SilentGhost I disagree. The linked question contains the answer to this question, but to anyone stumbling around looking for a relatively simple answer to the question asked here, the linked question will not seem at all the same. – David Berger Mar 10 '10 at 18:30
  • @David: and simple was already asked (quite recently too), you free to spend *your* time to find where it is, questions that have the same answers are duplicates in my book. – SilentGhost Mar 10 '10 at 18:40

4 Answers4

3

The == operator tests for equality

The is keyword tests for object identity; whether we are talking about the same object. Note that multiple variables may refer to the same object.

Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
2

The is operator compares the identity while the == operator compares the value. Essentially x is y is the same as id(x) == id(y)

Wolph
  • 78,177
  • 11
  • 137
  • 148
1

For implementation reasons, "odp" is a bad example, but you should not use is unless you want the possibility of two identical strings to evaluate to false:

>>> lorem1 = "lorem ipsum dolor sit amet"
>>> lorem2 = " ".join(["lorem", "ipsum", "dolor", "sit", "amet"])
>>> lorem1 == lorem2
True
>>> lorem1 is lorem2
False

As others have said, is tests identity, not equality. In this case, I have two separate strings with the same contents. However, you should not depend on this either:

>>> odp1 = "odp"
>>> odp2 = "".join(["o", "d", "p"])
>>> odp1 == odp2
True
>>> odp1 is odp2
True 

In other words, you should never use is to compare strings.

P.S. In Python 2.7.10 >>> odp1 is odp2 returns False.

AWalkmen
  • 33
  • 5
jcdyer
  • 18,616
  • 5
  • 42
  • 49
0

See here

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value

asdfg
  • 2,541
  • 2
  • 26
  • 25