Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's preferred comparison operators

Tags:

Is it preferred to do:

if x is y:     return True 

or

if x == y     return True 

Same thing for "is not"

like image 443
ensnare Avatar asked Apr 05 '10 03:04

ensnare


People also ask

What are the 4 Python comparison operators?

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 ( != ).

Which operator is used for comparison of values in Python?

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).


1 Answers

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 ids).

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 
like image 153
unutbu Avatar answered Nov 07 '22 07:11

unutbu