Search code examples
pythonoperators

What does 'is' operator do in Python?


I was (maybe wrongfully) thinking that is operator is doing id() comparison.

>>> x = 10
>>> y = 10
>>> id(x)
1815480092
>>> id(y)
1815480092
>>> x is y
True

However, with val is not None, it seems like that it's not that simple.

>>> id(not None)
2001680
>>> id(None)
2053536
>>> val = 10
>>> id(val)
1815480092
>>> val is not None
True

Then, what does 'is' operator do? Is it just object id comparison just I conjectured? If so, val is not None is interpreted in Python as not (val is None)?


Solution

  • You missed that is not is an operator too.

    Without is, the regular not operator returns a boolean:

    >>> not None
    True
    

    not None is thus the inverse boolean 'value' of None. In a boolean context None is false:

    >>> bool(None)
    False
    

    so not None is boolean True.

    Both None and True are objects too, and both have a memory address (the value id() returns for the CPython implementation of Python):

    >>> id(True)
    4440103488
    >>> id(not None)
    4440103488
    >>> id(None)
    4440184448
    

    is tests if two references are pointing to the same object; if something is the same object, it'll have the same id() as well. is returns a boolean value, True or False.

    is not is the inverse of the is operator. It is the equivalent of not (op1 is op2), in one operator. It should not be read as op1 is (not op2) here:

    >>> 1 is not None     # is 1 a different object from None?
    True
    >>> 1 is (not None)   # is 1 the same object as True?
    False