7.8 Identity Operators
Python's is and is not operators for comparing object identity rather than value, when to reach for them over == and !=, and how id() confirms what's being compared.
This section covers is/is not specifically as comparison operators. The underlying concept — a variable being a reference to an object, not the object itself — is covered in full in 6.2 Objects and Variable References.
is
What Is It?
Tests whether two names reference the exact same object in memory (same identity), not merely equal values.
>>> a = [1, 2, 3]
>>> b = a
>>> c = [1, 2, 3]
>>> a is b # same object
True
>>> a is c # equal value, but a DIFFERENT object
False
is not
>>> a is not c
True
Identity vs Equality
The Rule of Thumb
Use == to compare values (almost always what you want), and reserve is specifically for identity checks — most commonly x is None, since None is a singleton.
>>> a == c # equal value
True
id()
Directly inspecting the identities being compared — see also 5.10 Type Checking:
>>> id(a), id(c)
(140475706460992, 140475706462784) # different -- confirms a is c is False
Quick Interview Answer
“
istests identity — whether two names point at the exact same object — while==tests value equality. Two lists can hold identical values (==isTrue) while being two entirely separate objects (isisFalse). The standard rule of thumb is to use==for almost everything, and reserveisspecifically for identity checks likex is None, sinceNoneis a singleton and there’s exactly one object to ever compare against.”
Common Mistakes
- Using
isto compare values instead of==— see 7.14 Common Mistakes for why this can silently appear correct due to CPython’s small-integer caching and string interning. - Writing
x == Noneinstead of the idiomaticx is None—is Noneis both faster and immune to a custom__eq__onxthat might override equality behavior unexpectedly.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form