Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "is" and "==" in python? [duplicate]

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

Is

a == b

the same as

a is b

?

If not, what is the difference?

Edit: Why does

a = 1
a is 1

return True, but

a = 100.5
a is 100.5

return False?

like image 369
Matthew Avatar asked Oct 27 '09 23:10

Matthew


1 Answers

No, these aren't the same. is is a check for object identity - ie, checking if a and b are 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 the objects should represent the same thing (most common usage) and is if you mean the objects should be in identical pieces of memory (you'd know if you needed the latter).

Also, you can overload == via the __eq__ operator, but you can't overload is.

like image 177
Peter Avatar answered Sep 25 '22 19:09

Peter