In Python, everything is represented by objects or by relations between objects, including variables, functions, lists, etc. Every object has an identity, a type, and a value
Before comparing objects in Python, we should ask ourselves, whether we want to compare two objects for equality or identity.
Because in Python, two objects can be equal but not identical. For example, two variables can have the same value but may refer to two different objects.
Let’s understand this by comparing objects using different techniques.
Use == To Compare Two Objects For Equality
Use the ==
operator to compare two objects for equality. In the following example, the variable a
and b
are equal because they have the same value.
>>> a = 6
>>> b = 6
>>> a == b
True
Similalry, list1
and list2
with same value are equal.
>>> list1 = [1, 3, 5]
>>> list2 = [1, 3, 5]
>>> list1 == list2
True
Use ‘is’ To Compare Two Objects For Identity
Use the is
keyword to compare two objects for identity. Here, the list1
and list2
are identical because they point to the same object.
>>> list1 = [1, 3, 5]
>>> list2 = list2
>>> list1 == list2
True
>>> list1 is list2
True
But the following two list objects despite having the same value, are not identical, because they are pointing to two different objects.
>>> list1 = [1, 3, 5]
>>> list2 = [1, 3, 5]
>>> list1 == list2
True
>>> list1 is list2
False
Use __eq__ To Compare Two Class Objects
Two objects of the same class having the same attribute values will return False
when compared for equality using the ==
operator.
To override this default behaviour, define an __eq__
method inside the class.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
if (isinstance(other, Person)):
return self.name == other.name and self.age == other.age
return False
p1 = Person('Tom', 21)
p2 = Person('Tom', 21)
print(p1 == p2)
Output:
True