Comparison Operators
==
== is used to check if two variables have the same value.
x = 1 y = 1 print(x == y) # True
Comparing the value of two different objects will return True.
x = [1, 2, 3] y = [1, 2, 3] print(x == y) # True
is
NEVER use is operator to check if two objects have the same value.
Known as the identity operator.
is is used to check if two variables point to the same object.
- same object = residing at the same address in memory.
is will return True only when the objects being compared are the same object, which means they point to the same location in memory.
x = 1 y = 1 print(x is y) # True x = [1, 2, 3] y = x print(x is y) # True
When is is used to compare two different objects, it will return False even if the objects have the same value.
x = [1, 2, 3] y = [1, 2, 3] print(x is y) # False
Caveat
NEVER use is operator to check if two objects have the same value.
print(3 is 2+1) # True print(300 is 200+100) # False
3 is 2+1 will return True because small ints (-5 to 256) in Python are cached internally.
Since bigger numbers are not cached, 300 is 200+100 will return False.