educative.io

Comparison operator

num1 = 5
num2 = 10
num3 = 10
list1 = [6,7,8]
list2 = [6,7,8]

print(num2 is not num3) # Both have the same object
print(list1 is list2) # Both have the different objects

How come num1 and num2 are same objects but list1 and list2 are different even though both have same values?

In Python, small integers (i.e., -5 to 256) are often stored in a cache, referring to the same object in the memory. Therefore, num2 is not num3 returns False in the mentioned case.

On the other hand, lists are mutable objects, so when two variables are assigned different lists, even if they have the same elements, they refer to different objects in the memory. That’s why list1 is list2 returns False in the cited case.

The is operator checks if two variables refer to the same object in the memory. To check if two lists have the same values, we can use the equality operator ==, which returns True if the elements in both lists are equal, regardless of whether the lists refer to the same object in memory.

Happy learning at Educative.