Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
When can I rely on identity tests with the is operator in Python?
The is operator in Python tests for object identity, not equality. You can rely on identity tests in specific circumstances where object identity is guaranteed.
Understanding the is Operator
The is operator compares object identities using their memory addresses. The test a is b is equivalent to id(a) == id(b).
x = ["Paul", "Mark"]
y = ["Paul", "Mark"]
z = x
# Identity test
print("x is z:", x is z)
print("x is y:", x is y)
# Verify with id()
print("id(x):", id(x))
print("id(z):", id(z))
print("id(y):", id(y))
x is z: True x is y: False id(x): 140234567890432 id(z): 140234567890432 id(y): 140234567890816
When You Can Rely on Identity Tests
Identity tests are guaranteed to work reliably in three specific circumstances:
1. Variable Assignments
Assignments create new names but preserve object identity ?
original = [1, 2, 3]
new_name = original
print("new_name is original:", new_name is original)
print("Always guaranteed: True")
new_name is original: True Always guaranteed: True
2. Container References
Objects stored in containers maintain their identity ?
my_object = "hello"
container = [None]
container[0] = my_object
print("container[0] is my_object:", container[0] is my_object)
print("Always guaranteed: True")
container[0] is my_object: True Always guaranteed: True
3. Singleton Objects
Singletons like None, True, and False have guaranteed identity ?
a = None
b = None
print("a is b:", a is b)
x = True
y = True
print("x is y:", x is y)
a is b: True x is y: True
When NOT to Use Identity Tests
Large Integers
Python doesn't guarantee identity for large integers ?
a = 1000
b = 500 + 500
print("a is b:", a is b)
print("a == b:", a == b)
a is b: False a == b: True
String Concatenation
Dynamically created strings may not have the same identity ?
a = 'Amit'
b = 'Am' + 'it'
print("a is b:", a is b)
print("a == b:", a == b)
a is b: False a == b: True
Mutable Objects
New instances of mutable containers are never identical ?
a = [10, 20, 30]
b = [10, 20, 30]
print("a is b:", a is b)
print("a == b:", a == b)
a is b: False a == b: True
Best Practices
| Use Case | Use is | Use == |
|---|---|---|
| Comparing with None | ? Always | ? Never |
| Variable assignments | ? Safe | ? Also works |
| Comparing values | ? Unreliable | ? Always |
| Performance critical | ? Faster | ? Slower |
Conclusion
Use is for comparing with singletons like None, checking variable assignments, and container references. For value comparisons, always use == to ensure reliable results regardless of object identity.
