What is the difference between "==" and "is" operator in Python?
The is operator determines whether the two operands refer to an identical object or not. On the other hand, the == operator takes the operands’ values and compares them to check if they are equal.
Code
l1 = []l2 = []l3 = l1if (l1 == l2):print("True")else:print("False")if (l1 is l2):print("True")else:print("False")if (l1 is l3):print("True")else:print("False")l3 = l2if (l2 == l3):print("True")else:print("False")
Explanation
-
The output of the first
ifcondition isTrueas bothl1andl2are empty. -
The second
ifcondition returnsFalseasl1andl2point to different objects with the same value but different memory locations. -
The third
ifcondition returnsTrueas equatingl3tol1means both point to the same object. -
The fourth
ifcondition returnsTrueas equatingl3tol2means both point to the same object. This means they both have the same value as well.