What Are Identity Operators in Python?
In Python, identity operators check whether two variables refer to the same object in memory.
This is different from equality (==), which checks if the values are the same.
Python has two identity operators:
| Operator | Meaning |
|---|---|
is | True if both variables reference the same object |
is not | True if both variables reference different objects |
Why Identity Matters
Python variables are names bound to objects, and two variables can have the same value but refer to different objects in memory.
Identity operators tell us whether the object itself is the same, not just the value.
Examples of Identity Operators (with Input & Output Together)
1. is Operator
x = 5 y = 5 print(x is y) # Output: # TrueHere, small integers are interned (cached by Python), so x and y reference the same object.
2. is not Operator
a = [1, 2, 3] b = [1, 2, 3] print(a is not b) # Output: # TrueAlthough a and b have the same value, they are different objects in memory.
Identity vs Equality
The == operator checks value equality, whereas is checks identity
a = [4, 5, 6] b = [4, 5, 6] print(a == b) print(a is b) # Output: # True # False-
a == b→ True (same contents) -
a is b→ False (different objects)
When Identity Can Be Useful
Identity operators are often used to check for special singleton objects like None
result = None if result is None: print("No result found") # Output: # No result foundUsing is None is a Python best practice for checking absence of a value.
How Python Stores Small Objects
Python interns (caches) some small immutable objects like:
-
Small integers
-
Short strings
In these cases,ismight evaluate toTruefor variables with the same literal values.
Example:
a = "hello" b = "hello" print(a is b) # Output: # TrueThis works because Python may store one copy of the literal and reuse it.