Equality in Python

== (Same value)

== checks that two variables have the same value.

For standard objects

a = [1, 2]
b = []
b.append(1)
b.append(2)
a == b
False
123456789 == 123456789
True
a = 123456789
b = 123456788+1
a == b
False
a = (1, 2, 3)
b = [1, 2, 3]
a == b
False

For custom objects

For custom objects, == has to specified via the magic method __eq__.

class User:
    def __init__(self, username, email):
        self.username = username
        self.email = email

User("francois", "francois@ens-lyon.fr") == User("francois", "francois@ens-lyon.fr")
False
class User:
    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __eq__(self, other):
        if isinstance(other, User):
            return self.username == other.username and self.email == other.email
        return NotImplemented
User("francois", "francois@ens-lyon.fr") == User("francois", "francois@ens-lyon.fr")
True
class User2:
    def __init__(self, username, email):
        self.username = username
        self.email = email
User2("francois", "francois@ens-lyon.fr") == User2("francois", "francois@ens-lyon.fr")
False

is (Same object)

is means the same object. It means the same pointer, the same address because we point to the very same object.

class Person:
    pass

a = Person()
b = Person()
a is b
False
class Person:
    pass

a = Person()
b = a
a is b
True
a = 123456789
b = 123456789
a is b
False
a = 123456789
b = a
a is b
True
a = 123456789
b = 123456788+1
a is b
False
a = 2
b= 1+1
a is b
True
a = [1,2]
b = a
a is b
True
a = (1, 2, 3)
b = (1, 2, 3)
a is b
False

Summary

In German:

  • is is das selbe
  • == is das gleiche