Python: Difference between `is` and` == `?

Possible duplicate:
Python & lsquo; == & rsquo; vs & lsquo; is & rsquo; string comparison, & lsquo; is & rsquo; sometimes fails why?

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

if x is "odp":

if x == "odp":

+5
source share
4 answers

The operator ==checks the equality

Keyword test isfor object identification; Are we talking about the same object. Note that several variables can refer to the same object.

+4
source

is , == . x is y id(x) == id(y)

+2

"odp" - , , , false:

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

, , . . , :

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

, .

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

+1

Operators are , and not a tag for identifying an object: x is y true if and only if x and y are the same object. x does not mean y gives the opposite value

0
source

All Articles