We might think that the ==
operator and is
operator are the same or do the same operation in Python but that is not true. In this post, we will understand the differences between both of them.
1. ==
operator in Python
The ==
operator is used for comparing or equating the values of the operands on the right-hand side and the left-hand side.
Time for an example:
my_list_1 = []
my_list_2 = []
my_list_3 = my_list_1
# using the == operator
if (my_list_1 == my_list_2):
print("True")
else:
print("False")
if (my_list_2 == my_list_3):
print("True")
else:
print("False")
Output:
True
True
Note: It can be observed that the values inside the lists are being compared, which is the reason behind the above output. In our example, we have kept the lists empty, you can even try with lists that have some data in them.
2. is
operator in Python
The is
operator in python is used to check if both the operands (on the right-hand side and left-hand side) refer to the same python object or not.
Time for an example:
my_list_1 = []
my_list_2 = []
my_list_3 = my_list_1
if (my_list_1 is my_list_2):
print("True")
else:
print("False")
if (my_list_2 is my_list_3):
print("True")
else:
print("False")
if (my_list_1 is my_list_3):
print("True")
else:
print("False")
Output:
False
False
True
Note: Even though my_list_1
and my_list_2
are empty, they don't refer to the same object, hence the output is False. But my_list_1
and my_list_3
refer to the same location, hence its output is True. Checking the ids of these three lists will make this concept clear.
Let's print the ids for all the list objects:
my_list_1 = []
my_list_2 = []
my_list_3 = my_list_1
print(id(my_list_1))
print(id(my_list_2))
print(id(my_list_3))
Output:
1931978781384
1931932927368
1931978781384
It can be clearly seen that my_list_1
object and my_list_3
object have the same IDs, which means they refer to the same python object.
Conclusion:
In this post, we understood the differences between ==
and is
operator in Python.