What is the difference between "is" and "==" in python?

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

there is

a == b

      

the same as

a is b

      

?

If not, what's the difference?

Edit: Why

a = 1
a is 1

      

return True, but

a = 100.5
a is 100.5

      

return False?

+2


source to share


2 answers


No, they are not the same. is

- checking the identity of an object, that is, checking that a

and b

is exactly the same object. Example:

a = 100.5
a is 100.5  # => False
a == 100.5  # => True

a = [1,2,3]
b = [1,2,3]
a == b  # => True
a is b  # => False
a = b
a == b  # => True
a is b  # => True, because if we change a, b changes too.

      



So: use ==

if you mean that objects should represent the same thing (most common usage) and is

if you mean that objects should be in the same parts of memory (you would know).

Also, you can overload ==

using an operator __eq__

, but you cannot overload is

.

+12


source


As has already been clearly stated above.

: used for identity testing (identical "objects")

== : used to test equality (~~ same value)



Also keep in mind that Python uses string interning (as an optimization), so you might get the following strange side effects:

>>> a = "test"
>>> b = "test"
>>> a is b
True
>>> "test_string" is "test" + "_" + "string"
True

>>> a = 5; b = 6; c = 5; d = a
>>> d is a
True  # --> expected
>>> b is a
False # --> expected
>>> c is a
True  # --> unexpected

      

+5


source







All Articles