What does the identity operator is check in Python?
a) Equality of values
b) Memory address equality
c) Data type equality
d) None of the above
Answer:
b) Memory address equality
Explanation:
The is
operator in Python checks whether two variables point to the same memory location, meaning it checks if they are the same object. This is different from the ==
operator, which checks if the values of the objects are equal.
x = [1, 2, 3]
y = x
z = [1, 2, 3]
result1 = (x is y) # result1 is True, because x and y refer to the same object
result2 = (x is z) # result2 is False, because x and z are different objects with the same value
Using is
is particularly useful when you want to check if two references point to the same object, such as when working with complex data structures, or when you need to verify singleton objects like None
.
Understanding the difference between is
and ==
helps avoid common pitfalls in Python programming, especially when dealing with mutable objects like lists or dictionaries.