6. Identity Operators
Identity operators are used to compare the memory locations of two objects.
In Python, every object has a unique memory address (called identity), and these operators check whether two variables point to the same object in memory.
Types of Identity Operators:
- is
- is not
List of Identity Operators
Operator | Name | Description |
---|---|---|
is |
Identity Operator | Returns True if both variables refer to the same object (memory). |
is not |
Negative Identity | Returns True if both variables do not refer to the same object. |
Types of Identity Operators:
-
Identity Operator (is)
is checks if two variables refer to the same object in memory.
a = [1, 2] b = a print(a is b) # True
Output: True
Explanation:
Both
a
andb
point to the same list in memory. Hence,a is b
returns True. -
Negative Identity Operator (is not):
is not returns True if two variables do not refer to the same object.
x = [10, 20] y = [10, 20] print(x is not y) # True
Output: True
Explanation:
Even though
x
andy
have the same values, they are stored at different memory locations. So,x is not y
returns True.
Why Use Identity Operators?
They are useful when we want to:
- Check if two variables refer to the same object (not just same value).
- Differentiate between is and == (value vs identity).
- Understand reference handling in Python objects.
Example:
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b) # True
print(a is c) # False
print(a == c) # True
Explanation:
a is b
→ True because both refer to the same list in memory.a is c
→ False because c is a different list, even though the values are same.a == c
→ True because both have equal contents (value-wise).
Note: is
compares identities (memory address), while ==
compares values.
Where it is Used?
- To check if two variables point to the same object
- In memory management and object referencing
- Useful in conditions where identity check is more important than value
Summary
is
: True if both refer to same object in memoryis not
: True if both refer to different objects==
: Compares values- Identity ≠ Value