In this article, I will discuss the difference between the "==" and the "is" operators.
The "==" operator compares by checking for equality while the "is" operator, compares identities. The two examples below will strengthen our understanding:
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.
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.
🚀 For people who like video courses and want to kick-start a career in data science today, I highly recommend the below video course from Udacity:
📚 While for book lovers:
- "Python for Data Analysis" by Wes McKinney, best known for creating the Pandas project.
- "Hands-on Machine Learning with Scikit-Learn, Keras, and TensorFlow" by Aurelien Geron, currently ranking first in the best sellers Books in AI & Machine Learning on Amazon.
- "Deep Learning" by Ian Goodfellow research scientist at OpenAI.
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).
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.