Is it preferred to do:
if x is y: return True
or
if x == y return True
Same thing for "is not"
Summary. A comparison operator compares two values and returns a boolean value, either True or False . Python has six comparison operators: less than ( < ), less than or equal to ( <= ), greater than ( > ), greater than or equal to ( >= ), equal to ( == ), and not equal to ( != ).
Both “is” and “==” are used for object comparison in Python. The operator “==” compares values of two objects, while “is” checks if two objects are same (In other words two references to same object).
x is y
is different than x == y
.
x is y
is true if and only if id(x) == id(y)
-- that is, x
and y
have to be one and the same object (with the same id
s).
For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y
, then x == y
is also True. However, this is not guaranteed in general. Strictly speaking, x == y
is true if and only if x.__eq__(y)
returns True.
It is possible to define an object x
with a __eq__
method which always returns False, for example, and this would cause x == y
to return False, even if x is y
.
So the bottom line is, x is y
and x == y
are completely different tests.
Consider this for example:
In [1]: 0 is False Out[1]: False In [2]: 0 == False Out[2]: True
PS. Instead of
if x is y: return True else: return False
it is more Pythonic to write
return x is y
And similarly,
if x == y: return True else: return False
can be replaced with
return x == y
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With