In this article, I will discuss the difference between the "==" and the "is" operators.

books, pencils, laptop, and iphone on a desk
Photo by Aleks Dorohovich / Unsplash

The "==" operator compares by checking for equality while the "is" operator, compares identities. The two examples below will strengthen our understanding:


Example 1

Let’s now take a look at some real Python code.

a = [1, 2, 3] 
b = a
print(a)
print(b)
print(a==b)
print(a is b)

The two list objects look the same and that's why we get the expected result when we compare them for equality by using the "==" operator:

However, that doesn’t tell us whether a and b are actually pointing to the same object—how might we can find out?

The answer is to compare both variables with the "is" operator as we did above. This confirms that both variables are in fact pointing to one list object.


Example 2

Let’s see what happens when we create an identical copy of our list object. We can do that by calling list() on the existing list to create a copy:

a = [1, 2, 3] 
b = list(a)
print(a)
print(b)
print(a==b)
print(a is b)

What this result tells us is that b and a have the same contents but they are pointing to two different objects.


Recap

So, to recap, let’s try and break down the difference between is and == into two short definitions:

• An "is" expression evaluates to True if two variables point to the same (identical) object.

• An "==" expression evaluates to True if the objects referred to by the variables are equal (have the same contents).


Conclusion

This brings us to the end of this article. Hope you got a basic understanding of the difference between the "==" and the "is" operators.

‌If you liked this article, please consider subscribing to my blog. That way I get to know that my work is valuable to you and also notify you for future articles.‌
‌Thanks for reading and I am looking forward to hearing your questions :)‌
Stay tuned and Happy Machine Learning.


‌References