The idiomatic comparison in Python

08 Jul 2020 2 mins read edit

Some newbies in Python often improperly use the operators is and == without knowing how exactly they work and when to use each one. In this article, I’ll talk about the difference between them, and about the use cases of each one.

Spoiler: the main difference is that is compares IDs of objects to check if both the operands refer to the same object and cannot be overloaded, when == compares the values of the objects and can be overloaded using the magic method __eq__.

Have a look at this code:

>>> a = []
>>> b = []
>>> a == b # a.__eq__(b)
>>> a is b

That’s right a is not b, and here is why:

>>> a_id = id(a)
>>> b_id = id(b)
>>> a_id == b_id

Use case of «is»

Using operator is makes sense when you want to compare variable with a singleton-object, like None, Ellipsis and so on:


if some_object is Ellipsis:

Still, good:

if some_object is not None:

Bad (even it will work correctly, because None always equal to None):

if some_object == None:

It’s better to write it like this:

if not some_object:

or like this:

if some_object is None:

Use case of «==»

Using operator == makes sense when you interested in comparing the values of objects:

>>> a = []
>>> b = []
>>> a == b # [].__eq__([])
>>> c = 'isaak'
>>> d = 'Isaak'
>>> c == d.lower()

Keep in mind, that by default the magic method __eq__ inherited from object compares IDs of objects (because it knows nothing about values).

You can read more about __eq__ here.


  • Use is when you compare variable with a singleton-object.
  • Use == when you want to compare the values of the objects.