What the difference between “==” vs. “is” in Python

In this article, I’m going to talk about the difference between == and is. I see many people who are confused about that, and I will try to make it simple. Get ready.

Everything I talk about here is valid for CPython (the most popular one).

Everything Is an Object in Python

First of all, everything is an object in Python. In Python, when you say x = 5, you basically create an integer object. I will dive into what is happening in the background in another article (byte code, Pyobject, and some other stuff).

==

I will mostly focus on is because the == operator is super simple to explain. When you say 5 == 5, it compares these two objects and says if they are equal or not.

is

This is different. When you say x = 5 and run the source code, 5 (int object) is created in memory and its memory address doesn’t change.

You can find its memory address by using the id(x) function. So, the output of id(x) is the address of the object in memory. Let’s walk through an example.

a = ['python']
b = ['python']
print(id(a))  # output is 139731532973312
print(id(b))  # output is 139731532041472

Above, two list objects are created and allocated in memory at different addresses (look at outputs) so when you say a is b, you basically say id(a) == id(b), so it will return False because they are allocated to different places in memory. Let’s walk through another example

a = ['python']
b = a
print(id(a))  # output is 140629850170880
print(id(b))  # output is 140629850170880

What happened here? Why do they have the same ID? Let me explain.

In the first line, you create a list object and a is pointing to this object. In the second line, you said b = a. This basically means, b points to what a points to.

So, in the second line, b is pointing to the same object a is pointing to. The object memory address is still the same, thus, the ID for both is the same.

Conclusion

== and is compare different things. Be careful when you use them.

Check my GitHub respiratory, star it and follow me if you like. you can find useful python codes which I update as much as I can.

Thank you!

#python #data science #devops #backend

What the difference between “==” vs. “is” in Python
21.55 GEEK