Python - Identity Operators

python logo pixel art

Python has identity operators to check if two variables refer to the same object in memory.



`is` vs `==`

While the `==` operator checks for equality between values, the `is` operator checks for equality between memory references.

list0 = [1,2,3]
list1 = [1,2,3]
print(list0 == list1) # True
print(list0 is list1) # False

Examples

dict0 = { 'name': 'John Doe', 'years_old': 174 }
dict1 = { 'name': 'John Doe', 'years_old': 174 }
dict2 = dict0

print(dict0 is dict1) # False
print(dict0 is dict2) # True
print(dict0 is not dict1) # True
class CustomClass:
  x = 1
  y = 2

my_class0 = CustomClass()
my_class1 = CustomClass()

print(my_class0 is my_class1) # False