Understanding ‘==’ vs. ‘is’ in Python
Explaining which to use when
All of us have come across a situation while solving some problems in Python when we have to compare two objects. For this, many of us have used either the
But, it seems many of us are confused about which one to use in which situation.
Analyzing the Difference
In this post, I will be analyzing the basic difference between them.
For this, we will start with some analogy with twin cats. So, assume that you have twin cats which are very similar. They have the same charcoal fur and the same piercing green eyes. Just by looking, we can’t tell which one is which.
Now, come to our
is operators in Python.
== operator compares by checking for the equality. If these two cats were two Python objects, then if comparing them using the
== operator, it will return ‘Both cats are Equal’ as the answer.
is operator compares by checking for the identity. If we use
is for comparing them we will get ‘Both cats are not Equal’ as the answer.
To really understand this, we will write some code.
First, we will create a list named
a which contains elements
[3, 4, 5] and another list
b which will point to the list
Let's inspect these two lists. We can see that these looks point to the identical-looking list.
Because the two list objects look the same, we’ll get the expected result
when we compare them for equality by using the
However, that doesn’t tell us whether
b are actually pointing to
the same object. Of course, we know they are because we assigned
them earlier, but suppose we didn’t know — how might we find out?
The answer is to compare both variables with the
is operator. This
confirms that both variables are, in fact, pointing to one list object.
Now, let’s create another list
c using the
list() which contains the elements of the list
If we look at list
c, it looks similar to the list pointed to by
Now, we will compare
c using the
== operator gives
True because both of them have the same content.
Python is telling us that
a are pointing to two different objects, even though their contents might be the same.
So, to recap, let’s try and break down the difference between
== into two short definitions.
isexpression evaluates to
Trueif two variables point to the
same (identical) object.
==expression evaluates to
Trueif the objects referred to by
the variables are equal (have the same contents).
So, I think this post will clear your doubts about