Compare Two Objects For Equality in Python
The "==" operator
The == operator is used to compare two objects for equality in Python.
Example of comparing two strings in Python:
x = "Technology"
y = "Technology"
if x == y:
print("Is Equal")
else:
print("Not Equal")
The output of the above code is as follows:
Is Equal
Example of comparing two Numbers in Python:
x = 20
y = 40
if x == y:
print("Is Equal")
else:
print("Not Equal")
The output of the above code is as follows:
Not Equal
Example of comparing two Booleans in Python:
x = True
if x == True:
print("Is True")
else:
print("Is False")
The output of the above code is as follows:
Is True
The Python "is" Keyword
The "is" keyword is used to compare if two objects are same.
Here's an example to check if two objects are same:
a = "apple"
b = "apple"
print(a is b)
The output of the above code is as follows:
False
Another example:
list1 = [1,2,3,4]
list2 = [1,2,3,4]
result = list1 is list2
print(result)
The output of the above code is as follows:
False
The Python __eq__
The __eq__ method is used to compare two class instances.
Example:
class Customer:
def __init__(self, name, id):
self.name = name
self.id = id
def __eq__(self, other):
if (isinstance(other, Customer)):
return self.name == other.name and self.id == other.id
else:
return False
object1 = Customer("Danny", 1)
object2 = Customer("Danny", 1)
x = object1 == object2
print(x)
The output of the above code is as follows:
True