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 might be aware of.
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 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 surprise with the output?
- When you use “b = a”, it does not create a new list. In fact, it creates 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 new list object. Now list ‘a’ and ‘c’ have same data but occupies 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 object. 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 Difference Between is and == in Python. I know its little confusing. If you have any comment, feel free to write below.