Difference between "is" keyword and "==" (double equal) in Python

Introduction

In Python, you may know there are two basic ways to compare if two variables are the same. The first one is is keyword, the second one is == operator. So what's the difference when we use them to compare something?

Let's see the code below:

>>> a = [1, 2, 3] >>> b = a >>> b is a True >>> b == a True >>> b = a[:] >>> b is a False >>> b == a True

a is list object, while b is initialized as a reference to object a. That is, b is pointing to the same object as a. So we will get True no matter comparing with is or ==.

Line b = a[:] will create copy the whole content in a to b, b is no more a reference to a. This time, is returns False and == returns True.


Another Consideration

You might also find out that in the code below, is is not working as expected.

>>> c = 10 >>> d = 10 >>> c is d True >>> c == d True >>> e = 1000 >>> f = 1000 >>> e is f False

Why? The reason is Python will cache some small integers? so that any variable given a value in that range will be pointed to the same object in memory. The cache range should be [-5, 256] as you can test out using below code:

for i in range(-10, 300): a = i + 1 - 1 print("%d, %s" % (i, i is a))

Seems like it is an implement detail in Python language, we may not need to consider too much about it.


Conclusion

  • is keyword is judging if the two comparators are the same object. We could also say, it's for reference equality.
  • == operator is for value equality. judging if the values in comparators are the same, it does not care if they are exactly the same thing.
Total Views: 4650

Search


Categories