What is difference between == and is ?⚡

A seemingly common Python interview question, but a crucial concept behind it. Let’s take a quick look.

In Python, we use the == operator to check if two objects have the same elements. :bulb:

In other words, it checks for equality of the values.

Whereas, the is operator checks if the 2 objects refer or point to the same object.:bulb:

Take a look at the code in the image.

I initialize 2 lists a and b with the same elements. So, when I check if a == b, it returns True.

But, a is b returns False, as they are pointing or referring to two different objects in the memory.:thinking:

This can also be verified by checking the id() of the lists, which will be different in this case.:bulb:

Now, when I make a = b explicitly, I am essentially making them point to the same object.

So, the is operator will return True, as the id() will be the same for both a and b.

And in the last step, when I re assign an object to list a, it doesn’t apply to b, so the id are different again. Neither == nor is will hold True now.

Now, a question for you. What if I appended a new value to the list a rather than re assigning in the last step above? :thinking:

What will the is operator return in that case - True or False?:question::question:

#python #datascience #machinelearning