Python provides identity operators to compare whether two variables refer to the same object in memory.
These operators are different from comparison operators because they do not compare values—they compare memory identity.
🧠 What are Identity Operators?
Identity operators are used to check if two variables point to the same object.
👉 In simple words:
- They check “Are these two variables the same object?”
⚙️ Types of Python Identity Operators
Python has two identity operators:
🟢 1. is Operator
The is operator returns True if both variables refer to the same object in memory.
Example:
a = [1, 2, 3]
b = a
print(a is b)
Output:
True
🔴 2. is not Operator
The is not operator returns True if variables do NOT refer to the same object.
Example:
a = [1, 2, 3]
b = [1, 2, 3]
print(a is not b)
Output:
True
🧪 Identity vs Equality
This is very important to understand:
🔍 Equality (==) checks value
🧠 Identity (is) checks memory location
Example:
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True (same values)
print(a is b) # False (different objects)
📦 Identity with Immutable Objects
Python may reuse memory for small immutable objects.
Example:
a = 10
b = 10
print(a is b)
👉 Sometimes this returns True due to internal optimization.
📚 Identity Operators Summary
| Operator | Meaning | Example | Result |
|---|---|---|---|
| is | Same object | a is b | True/False |
| is not | Different object | a is not b | True/False |
🚀 Where Identity Operators are Used?
Identity operators are used in:
- Memory management 🧠
- Object comparison 🧾
- Singleton patterns 🔐
- Performance optimization ⚙️
- Internal Python operations 🐍
🧪 Real Example: None Check
x = None
if x is None:
print("Value is empty")
👉 This is the recommended way to check for None.
🧾 Conclusion
Python identity operators help you check whether two variables point to the same object in memory. They are essential for understanding how Python handles objects internally.
💡 Final Thought
If you understand identity operators, you gain deeper insight into how Python manages memory and objects.


0 Comments