Comparisons in Python: the difference between “is” and “==”

Adrienne Domingus
3 min readJan 19, 2020

Comparing one thing to another is constant in programming. But Python has two ways to do this: == and is. So what’s the difference, anyway?

Let’s give ourselves a class to work with as we see how this all works. A cat, obviously.

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

You’ll notice we’ve defined an __eq__ method on our Cat class: this lets us give a custom definition for what it means for two objects to be equal (docs here). In this case, we’ve said that if two cats have the same name, they equal each other.

Ok, let’s instantiate some instances of cats, Mena and Llewyn, and another cat, also named Mena, but not my cat Mena, and compare them:

My cat, Mena, on the left, and my brother’s cat Llewyn on the right. This post needed some cats 🤷‍♀️
>>> mena = Cat("Mena")
>>> llewyn = Cat("Llewyn")
>>> another_cat_named_mena = Cat("Mena")
>>> mena == llewyn
False
>>> mena == another_cat_named_mena
True

This aligns with what we’d expect, given how we defined equality on Cat above: mena and another_cat_named_mena have the same name, so we’ve decided they’re equal. But they’re not actually the same cat. Let’s prove it! Every object in Python is assigned a unique id, which…

--

--