Identity Operators in Python
Python Identity Operators
Python identity operators are used to determine whether two variables refer to the exact same object in memory, as opposed to merely having the same value. They check for object identity, not just value equality.
There are two identity operators in Python:
is operator:
This operator returns True if both operands refer to the same object in memory.
It returns False otherwise.
Python
a = [1, 2, 3]
b = a # b refers to the same list object as a
c = [1, 2, 3] # c is a new list object with the same content
print(a is b)
Output: True
print(a is c)
Output: False
is not operator:
This operator returns True if both operands do not refer to the same object in memory.
It returns False otherwise.
Python
x = "hello"
y = "world"
z = "hello"
print(x is not y)
Output: True
print(x is not z)
Output: False (due to string interning for short strings)
Note-
It is important to differentiate identity operators (is, is not) from equality operators (==, !=). Equality operators compare the values of objects, while identity operators compare the memory locations (object identities) of objects. Two objects can have the same value but be distinct objects in memory.
 
 
 
 
 
 
 

No comments: