What is the Difference Between is and == in Python?
It’s really confusing for Python programmer. When to use ‘is’? When to use ‘==’?
And what is the Difference Between is and == in Python?
Before getting into the difference here is quick syntax, you should understand.
A syntax for “is” expression:
a is b
A Syntax for “==” (equals) expression:
a == b
Note: Where ‘a’ and ‘b’ are two different Python objects.
If we consider it as a native language, both expression seems to be doing the same work. But does not hold true for Python.
So to find the difference between them, let’s make it simple.
I will give you quick demonstration by using ”is” and “==” expressions with Python list.
Difference Between is and == in Python | “is” vs “==”
- The “is” expressions in Python evaluates and returns to True if two variables point to the same Python data object.
- The “==” expression holds True if the objects referred to by the variables are equal.
Without getting heedless, let’s take the example of using “is” and “==” on the Python list.
“is” expression with List object:
a = [1, 2, 3]
b = a
a is b
#True
c = list(a)
a is c
#False
So are you surprised by the output?
- When you use “b = a”, it does not create a new list. In fact, it creates a pointer pointing to the same list. As ‘a’ and ‘b’ points to the same list, ‘is’ expression returns True.
- When you use “c = list(a)”, it copies all the list values from list ‘a’ and creates a new list object. Now list ‘a’ and ‘c’ have the same data but occupies a different memory location. As ‘a’ and ‘c’ are two different lists, ‘is’ expression returns False.
Then how “==” (equals) is different from “is”?
“==” expression with List object:
a = [1, 2, 3]
b = a
a == b
#True
c = list(a)
a == c
#True
- As told above, expression “b = a” does not create a new list so the content will be the same pointed by two different list objects. So it will return True if you do “a == b”.
- “c = list(a)” creates new list but both the list carries same data contents. So “a == c” evaluates to True.
Related read to explore Python List:
This is all about the Difference Between is and == in Python. I know its little confusing. If you have any comment, feel free to write below.
I am a Python enthusiast who loves Linux and Vim. I hold a Master of Computer Science degree from NIT Trichy and have 10 years of experience in the IT industry, focusing on the Software Development Lifecycle from Requirements Gathering, Design, Development to Deployment. I have worked at IBM, Ericsson, and NetApp, and I share my knowledge on CSEstack.org.