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.