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 = l1
if (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 = l2
if (l2 == l3):
print("True")
else:
print("False")

Explanation

  • The output of the first if condition is True as both l1 and l2 are empty.

  • The second if condition returns False as l1 and l2 point to different objects with the same value but different memory locations.

  • The third if condition returns True as equating l3 to l1 means both point to the same object.

  • The fourth if condition returns True as equating l3 to l2 means both point to the same object. This means they both have the same value as well.

New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources