Introduction π
Identity operators are used to compare the **memory location** of two objects. Instead of checking if two values are equal, identity operators check whether the variables refer to the **same object** in memory.
Note
1. List of Identity Operators π
| Operator | Meaning | Example |
|---|---|---|
| is | True if both variables reference the same object | x is y |
| is not | True if variables reference different objects | x is not y |
2. Using the "is" Operator π
is checks whether two variables point to the exact same object (same memory address).
is_operator.py
x = 10
y = 10
print(x is y) # True (small integers are cached)
print(x == y) # True (same value)Note
βοΈ x == y checks value
These are NOT the same!
3. Using the "is not" Operator π«
Returns True if the variables reference different objects.
is_not_operator.py
a = ["apple", "banana"]
b = ["apple", "banana"]
print(a == b) # True (same content)
print(a is b) # False (different objects)
print(a is not b) # TrueNote
4. Identity Operators vs Equality Operators βοΈ
| Operator | Checks | Example |
|---|---|---|
| == | Value equality | [1, 2] == [1, 2] β True |
| is | Object identity (same memory) | [1, 2] is [1, 2] β False |
Note
5. Identity With Mutable vs Immutable Types π§
Immutable types (int, float, str, tuple)
Python often reuses small immutable objects, so identity checks may return True.
immutable_identity.py
x = "hello"
y = "hello"
print(x is y) # True (string interning)Mutable types (list, dict, set)
Mutable types always create new objects β identity is usually False.
mutable_identity.py
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True
print(a is b) # False6. Checking None With Identity Operators π’
The preferred way to compare with None is using is, not ==.
none_check.py
value = None
if value is None:
print("Value is None")
if value is not None:
print("Value is not None")Note
7. Real-World Example π
real_world.py
# check if caching applied
x = 256
y = 256
print(x is y) # True (caching)
x = 257
y = 257
print(x is y) # False (new objects)Conclusion π
You now understand how Python identity operators work! Want the next tutorial on Membership Operators, Conditional Statements, Loops, or Control Flow? Just tell me! π