Python 3 – Identity Operators Example
Python 3 provides two identity operators that can help determine if two variables refer to the same object: is
and is not
. These operators can be useful in certain situations where you need to compare objects by their identity rather than their value.
The is
Operator
The is
operator is used to compare the memory location of two objects. In other words, it checks whether the two variables refer to the same object in memory. The syntax for using the is
operator is quite simple:
x is y
In the above code snippet, the is
operator will return True
if x
and y
both refer to the same object in memory. If they don’t, it will return False
.
Let’s take a look at some examples to better understand how the is
operator works:
# Example 1
x = [1, 2, 3]
y = [1, 2, 3]
print(x is y) # Output: False
# Example 2
x = [1, 2, 3]
y = x
print(x is y) # Output: True
In Example 1, x
and y
are two different objects that happen to have the same value. Therefore, the is
operator returns False
. In Example 2, x
and y
both refer to the same object ([1, 2, 3]
) in memory, so the is
operator returns True
.
The is not
Operator
The is not
operator is the negation of the is
operator. It checks whether two variables do not refer to the same object in memory. The syntax for using the is not
operator is as follows:
x is not y
In the above code snippet, the is not
operator will return True
if x
and y
do not refer to the same object in memory. If they do, it will return False
.
Here’s an example to illustrate how the is not
operator works:
# Example 3
x = [1, 2, 3]
y = [1, 2, 3]
print(x is not y) # Output: True
In Example 3, x
and y
are two different objects that happen to have the same value. Therefore, the is not
operator returns True
.
Conclusion
The is
and is not
operators in Python 3 are used to compare the memory location of two objects. They can be useful in situations where you need to compare objects by their identity rather than their value. However, you should use them with caution, as they can lead to unexpected behaviour if not used correctly.