Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Numbers and Binary Data

Python is and is not operators

Reference for Python's is and is not operators: compare object identity, when to use them with None, why == differs, and the small-integer and string caching trap.

a is b is true when a and b are the very same object in memory. a is not b is its negation. Unlike ==, which asks "do these have equal values?", is asks "is this one object with two names?".

The operator cannot be overloaded, so it always means exactly this and costs almost nothing. Its main job in real code is comparing with the singletons None, True, False and ....

Python
x = None
x is None        # True
[] is []         # False: two separate lists

Try it

Python Same value, same object?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Where is can surprise you

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
a is b
a is not b

Return value: a bool. a is not b is equivalent to not (a is b), and x is not None reads as one operator, not as x is (not None).

Raises: nothing. Identity is defined for every pair of objects.

Usage notes

  • Use is for None. if x is None: is correct, faster, and immune to classes whose __eq__ claims to equal everything (as the example shows). The same goes for True, False, NotImplemented and Ellipsis, although for booleans you usually just write if x:.
  • Do not use is for numbers, strings or tuples. CPython caches small integers (-5 to 256) and may reuse equal string or constant objects, so is sometimes gives True for equal values and sometimes not, depending on how the values were created. Python 3.8 and later even warns about x is 1 with a SyntaxWarning. Use ==.
  • Mutable objects are not cached. Two list, dict or set literals are always distinct, so [] is [] is False and [] == [] is True.
  • Aliasing. b = a does not copy; both names refer to one object. is is the quickest way to check that. See copy for shallow and deep copies.
  • id() backs the test. In CPython a is b is the same as id(a) == id(b), but is is cleaner and does not create integers.
  • Sentinels. A module-level _MISSING = object() is a classic unique default value to detect "argument not supplied", and is is the only correct way to test for it.
  • Precedence. is is one of the comparison operators and chains like them, so a is b is c means a is b and b is c.