What’s the difference between '==' and 'is' in Python?


What's the difference between == and is?

Let's find out👇

== is an equality operator. It checks whether two objects are equal by their values. To compare, objects must have an __eq__ method implemented.

my_list = [1, 2, 3]
another_list = [element for element in my_list]
print(my_list == another_list)
# => True


class User:
    def __init__(self, name):
        self.name = name

    def __eq__(self, other):
        return other.name == self.name


user1 = User(name="Jan")
user2 = User(name="Jan")
print(user1 == user2)
# => True

is is an identity operator. It checks whether you're referencing the same object on both sides of the comparison. It doesn't care about the values.

my_list = [1, 2, 3]
another_list = [element for element in my_list]
print(my_list is another_list)
# => False


class User:
    def __init__(self, name):
        self.name = name


user1 = User(name="Jan")
user2 = User(name="Jan")
print(user1 is user2)
# => False
print(user1 is user1)
# => True

When should you use one over the other?

Use== when you care about values and use is when you care about actual objects.