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 ....
x = None x is None # True [] is [] # False: two separate lists
Try it
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.
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
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
isforNone.if x is None:is correct, faster, and immune to classes whose__eq__claims to equal everything (as the example shows). The same goes forTrue,False,NotImplementedandEllipsis, although for booleans you usually just writeif x:. - Do not use
isfor numbers, strings or tuples. CPython caches small integers (-5 to 256) and may reuse equal string or constant objects, soissometimes givesTruefor equal values and sometimes not, depending on how the values were created. Python 3.8 and later even warns aboutx is 1with aSyntaxWarning. Use==. - Mutable objects are not cached. Two list, dict or set literals are always distinct, so
[] is []isFalseand[] == []isTrue. - Aliasing.
b = adoes not copy; both names refer to one object.isis the quickest way to check that. Seecopyfor shallow and deep copies. id()backs the test. In CPythona is bis the same asid(a) == id(b), butisis cleaner and does not create integers.- Sentinels. A module-level
_MISSING = object()is a classic unique default value to detect "argument not supplied", andisis the only correct way to test for it. - Precedence.
isis one of the comparison operators and chains like them, soa is b is cmeansa is b and b is c.