What is the difference between == and the command is in Python?

March 14, 2022

What is the difference between == and the command is in Python?

In this article we will learn the difference between == and the is command in Python, with practical examples and where to use each of the operators.

First let’s learn the concepts, as the two operators are not similar, each has its own distinct role.

The == operator is used to test equality between two objects.

The  βisβ operator will test the identity of an object

That is, if one object is equal to the other

Let’s look at some practical examples:

```print(1 == 1) # True
print(1 is 1) # True
print(1+1 == 2) # True
print(1+1 is 2) # True
print("a" + "b" == "ab") # True
print("a" + "b" is "ab") # True
```

The answers will be True for all cases, but so what? Where’s the difference?

You will 99.99% of the time receive the same value, because if the object is the same, its values also coincide

However, it is good to understand this subtle difference between the two operators

```a = []
b = []
print(a == b)
print(a is b)
```

See the example of this case, the value is the same, but it is not the same object

These are the cases you won’t get the same answer

And it is also the case that proves that operator is checks the origin of the object and not the value itself

Differing one operator from another π

Conclusion

In this article we learned the difference between == and the βisβ command in Python

We can understand that both are different, because the == compares values and the is the origin of the object

So in most cases we will have equal values for the comparisons

Only in specific cases, when the value is the same and the origin of the object is different, will we have a difference in the answer

Subscribe
Notify of