Python – Identity Operators
Identity Operators are used to check if two variables point to same reference of an object in Python. The following table lists out the two Identity operators in Python.
Operator Symbol | Description | Example |
---|---|---|
is | Returns True if both operands refer to same object. | x is y |
is not | Returns True if two operands refer to different objects. | x is not y |
Two objects are said to have same reference, if they have same id value. id is a property of the object which can be accessed using Python Builtin function id().
Tutorials
The following tutorials cover each of the identity operators in detail.
Examples
In the following program, we shall print the ids of x and y, along with the results of is and is not operators.
main.py
x = [1, 2, 3]
y = x
print(x is y) # True
print(x is not y) # False
print(id(x))
print(id(y))
Output
True
False
2284566373000
2284566373000
We have assigned the value of x to y. Now, both x and y store the reference to same object in memory. Therefore, x is y.
main.py
# is operator
x = [1, 2, 3]
y = [1, 2, 3]
print(x is y) # True
print(x is not y) # False
print(id(x))
print(id(y))
Output
False
True
1961841222280
1961841222344
Even though the list elements are same, x and y are assigned with two different list objects. Hence, the ids are different for x and y and therefore x is not y, in this case.
Conclusion
In this Python Tutorial, we learned how to check if two variables hold the same object or different objects using Identity Operators.