Search code examples
pythoncomparison

Python's preferred comparison operators


Is it preferred to do:

if x is y:
    return True

or

if x == y
    return True

Same thing for "is not"


Solution

  • 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