Identity Operators
Python · Operators
Theory
is and is not check whether two names refer to the very same object in memory, by comparing identities (what id() returns). == instead asks whether two objects have equal values. With a = [1, 2, 3], b = a and c = [1, 2, 3]: a is b is True because both names point to one list, while a is c is False because c is a separate list that merely holds the same values, even though a == c is True.
The main correct use of is is checking for singletons, objects Python guarantees exist only once: None, True and False. Write if value is None, not == None. Avoid is for numbers and strings: CPython reuses some small integers and short strings for efficiency, so 5 is 5 may happen to be True while larger values behave differently. That is an implementation detail, not a language rule, so results can change between Python versions and contexts.
Why we use it
Sometimes you need to know whether two variables are aliases of one object, for example to understand why changing one list changed 'another'. is answers that question, and is None is the clear, reliable way to test for a missing value.
When to use it
Use is / is not only for None, True, False or when you deliberately check aliasing. Use == for comparing values of numbers, strings, lists and everything else.
How it works
- Evaluate a is c
- Get the identity (memory object) of a
- Get the identity of c
- Are they the exact same object? Yes: Return True. No: Return False, even if the values are equal.
- print(a is b, a is c) shows True False
Syntax
a is b
a is not bExample
a = [1,2,3]
b = a
c = [1,2,3]
print(a is b, a is c)Key points
- is checks identity; == checks equality of values
- a is b can be False even when a == b is True
- Always write x is None, not x == None
- Do not use is to compare numbers or strings; small-value caching is an implementation detail
- id(x) shows the identity that is compares