Compare Two Objects For Equality in Python

The "==" operator

The == operator is used to compare two objects for equality in Python.

Comparing Two strings in Python

Example

x = "Technology"
y = "Technology"
if x == y:
    print("Is Equal")
else:
    print("Not Equal")
Output
Is Equal

Comparing Two Numbers in Python

Example

x = 20
y = 40
if x == y:
    print("Is Equal")
else:
    print("Not Equal")
Output
Is Not Equal

Comparing Two Booleans in Python

Example

x = True
if x == True:
    print("Is True")
else:
    print("Is False")
Output
Is True

The Python "is" Keyword

The is keyword is used to compare if two objects are same.

Example

a = "apple"
b = "apple"
print(a is b)
Output
False
Example

list1 = [1,2,3,4]
list2 = [1,2,3,4]

result =  list1 is list2
print(result)
Output
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)
Output
True