Identity Operators
3 min read ·
Identity operators in Python are used to compare the memory location (identity) of objects, not just their values.
They answer the question:
Do both variables refer to the same object in memory?
Python provides two identity operators:
isis not
What Are Identity Operators?
Identity operators check whether two variables point to the same object.
Both may look similar, but they are very different checks.
Identity Operators Table
| Operator | Description |
|---|---|
is | Returns True if both variables refer to the same object |
is not | Returns True if both variables refer to different objects |
is vs == (Most Important Concept)
| Operator | What it checks |
|---|---|
== | Value equality |
is | Memory identity |
Example
Explanation:
==→ values are equalis→ different objects in memory
Identity Operators with Immutable Types
Python may reuse memory for small immutable objects.
This happens due to interning.
Identity Operators with Mutable Types
Mutable objects usually do not share memory.
When Identity Becomes True for Mutable Objects
Both variables point to the same list.
Identity Operator with None (Best Practice)
The correct way to check for
None is using is.Why is Is Preferred for None
Using
is avoids unexpected behavior.Identity Operators with Functions
Both refer to the same function object.
Identity Operators with Boolean Values
Explanation:
True == 1→TrueTrue is 1→False
Identity Operators with Integers (Tricky)
Small integers may be cached; larger ones usually are not.
Common Mistakes
Mistake 1: Using is for value comparison
Unreliable ❌
Correct:
Mistake 2: Using == to check None
Correct:
Practice
- Compare two lists using
==andis - Assign one variable to another and test identity
- Check a variable against
Noneusingis - Predict outputs of identity comparisons