Identity operators are used to compare the memory locations of two objects. They are used to check if two variables refer to the same object in memory.
Types of Identity Operators
is
: ReturnsTrue
if the operands refer to the same objectis not
: ReturnsTrue
if the operands do not refer to the same object
is
operator
x = [1, 2, 3]
y = [1, 2, 3]
z = x
print(x is y) # Output: False
print(x is z) # Output: True
is not
operator
x = [1, 2, 3]
y = [1, 2, 3]
z = x
print(x is not y) # Output: True
print(x is not z) # Output: False
In the above examples, x
and y
are different objects, so x
is y returns False
, while x
is z
returns True
because x
and z
refer to the same object in memory. The is not
operator works in the opposite way, returning True
if the operands are not the same object, and False
if they are.
Difference between is
and ==
It is important to understand the difference between the ==
and is
operators, ==
operator is used to compare the values of two variables, while is
operator is used to compare the memory location of two variables.
In some cases, two variables can have the same value but different memory locations.
Similarly: is not
and !=
operator works
The Confusion
a = 1
b = 1
print(a is b) # True
print(a == b) # True
Here, we have taken two variables a
and b
, and assigned them the same value 1
then
a == b
returns True
as well as a is b
returns True
.
This happened because variables that have the same value will be assigned to the same memory location.
id()
: This function takes an argument and returns the memory address of that argument.
a = 1
b = 1
print(id(a), id(b))
# 2182716063984 2182716063984
print(id(a) == id(b))
# True
Here, the memory locations of two different variables with the same value are also the same. That's why is
operator returns True
.
In summary, the identity operators are used to compare the memory location of two objects and are useful in determining if two variables refer to the same object in memory.