Common mistakes we make in Python and why we should avoid that part 2

Posted by Afsal on 27-Aug-2021

Hi Pythonistas!

This is part 2 of the series. If you are new, you can check part 1 here

Today we are going to discuss "is vs ==". In Python, sometimes we use is and == operators interchangeably. It will work at times, but not always. Let me explain this with an example.

Before getting into the topic, we all should know something about a Python object. Every Python object has two things in common:

  •  First, its memory reference - Memory id can be found using the id function.
  • Second, its value

What does ‘is’ operator do:

The is operator checks whether two objects are pointing to the same memory location.

What does ‘==’ operartor do:

The == operator checks if the value of the operator is the same.

>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a == b
True
>>> a is b
False
>>> id(a)
140281424436160
>>> id(b)
140281424966208

Here in this example, we can see that contents of a and b are same, but the is operator returns false and == returns true.

>>> a = [1,2,3]
>>> b = a
>>> a == b
True
>>> a is b
True
>>> id(a)
140281424966208
>>> id(b)
140281424966208
>>>

Here in this example, both is and == return the same result as both of them are pointing to the same memory location.

Note: For small common strings and integers in the range -5 to 256 the memory location will be the same. Python does this for optimization. This is a big topic that can be discussed later on in an article.

What is the solution:

If you are checking equality, then always use the == operator. Use is operator only when you are checking if an object is the same as another like a is None.

happy coding !!