The == operator compares the values of both the operands and checks for value equality. Whereas is operator checks whether both the operands ask an equivalent object or not.

# python3 code to  
# illustrate the
# difference between
# == and is operator
# [] is an empty list
list1 = []
list2 = []
list3=list1

if (list1 == list2):
print("True")
else:
print("False")

if (list1 is list2):
print("True")
else:
print("False")

if (list1 is list3):
print("True")
else:
print("False")

OUTPUT :

True
False
True
  • Output of the primary if condition is “True” as both list 1 and list 2 are empty lists.
  • Second if condition shows “False” because two empty lists are at different memory locations. Hence list 1 and list 2 ask different objects. we will check it with id () function in python which returns the “identity” of an object.
  • Output of the third if condition is “True” as both list 1 and list 3 are pointing to an equivalent object.
list1 = [] 
list2 = []

print(id(list1))
print(id(list2))

OUTPUT :

139877155242696
139877155253640

 

Categorized in: