Comparison by is vs

suggest change

A common pitfall is confusing the equality comparison operators is and ==.

a == b compares the value of a and b.

a is b will compare the identities of a and b.

To illustrate:

a = 'Python is fun!'
b = ''.join(['Python is ', 'fun!'])
a == b # returns True
a is b # returns False

a = [1, 2, 3, 4, 5]
b = a      # b references a
a == b     # True
a is b     # True
b = a[:]   # b now references a copy of a
a == b     # True
a is b     # False [!!]

Basically, is can be thought of as shorthand for id(a) == id(b).

Beyond this, CPython reuses some objects, and that reuse is not part of the language. Identical literals in the same code are often one object, so is can be true for a long string or for 1000. Do not rely on that. Small integers from -5 through 256 are cached, so separately computed values in that range can still be the same object. Larger integers are not.

a = 'not so short'
b = ''.join(['not ', 'so short'])
a == b  # True
a is b  # False

c = 1000
d = int('1000')
c == d  # True
c is d  # False

e = 5
f = int('5')
e is f  # True on CPython: 5 is in the small-int cache

You should use is to test for None:

if myvar is not None:
    # not None
    pass
if myvar is None:
    # None
    pass

A use of is is to test for a “sentinel” (i.e. a unique object).

sentinel = object()
def myfunc(var=sentinel):
    if var is sentinel:
        # value wasn’t provided
        pass
    else:
        # value was provided
        pass

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents