# 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 `==` or `is` operator.

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 `==` vs `is` operators in Python.

The `==` 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.

The `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 `a`.

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 `==` operator.

However, that doesn’t tell us whether `a` and `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 `a`.

If we look at list `c`, it looks similar to the list pointed to by `a` and `b`.

Now, we will compare `a` and `c` using the `==` and `is` operators.

Here, the `==` operator gives `True` because both of them have the same content.

Python is telling us that `c` and `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 `is` and
`==` into two short definitions.

1. An `is` expression evaluates to `True` if two variables point to the
same (identical) object.
2. A `==` expression evaluates to `True` if the objects referred to by
the variables are equal (have the same contents).

So, I think this post will clear your doubts about `==` and `is`.

Written by

Written by

## Diwakar Singh Parmar

#### Software Engineer at Concentric.ai | Graduate from IIT Kharagpur 