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 to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources