Some newbies in Python often improperly use the operators
== 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
Have a look at this code:
>>> a =  >>> b =  >>> a == b # a.__eq__(b) True >>> a is b False
a is not
b, and here is why:
>>> a_id = id(a) 4464140992 >>> b_id = id(b) 4465176960 >>> a_id == b_id False
is makes sense when you want to compare variable with a singleton-object,
Ellipsis and so on:
if some_object is Ellipsis: do_some_stuff()
if some_object is not None: do_other_stuff()
Bad (even it will work correctly, because
None always equal to
if some_object == None: do_some_stuff()
It’s better to write it like this:
if not some_object: do_some_stuff()
or like this:
if some_object is None: do_some_stuff()
== makes sense when you interested in comparing the values of objects:
>>> a =  >>> b =  >>> a == b # .__eq__() True >>> c = 'isaak' >>> d = 'Isaak' >>> c == d.lower()
Keep in mind, that by default the magic method
__eq__ inherited from
IDs of objects (because it knows nothing about values).
You can read more about
iswhen you compare variable with a singleton-object.
==when you want to compare the values of the objects.