educative.io

Educative

Comparison Operators - Learn Python 3 from Scratch

why list 1 is not list2 both have same no.?

Hi @Preeti_Kothiyal !!
In Python, lists are mutable objects, which means that they can be changed after they are created. When you create a list, Python allocates a block of memory to store the elements of the list. If you create two separate lists with the same elements, Python will allocate two separate blocks of memory to store the elements of each list.

In this example, list1 and list2 are two separate lists with the same elements, so they are allocated separate blocks of memory. This is why list1 is list2 evaluates to False.
The is keyword in Python tests if two variables refer to the same object in memory. In this case, although list1 and list2 have the same elements, they are two separate objects in memory, so list1 is list2 will evaluate as False.

To illustrate this, you can use the id() function in Python to check the identity of the objects:

list1 = [6,7,8]
list2 = [6,7,8]
print(id(list1))
print(id(list2))

This will output two different memory addresses, indicating that list1 and list2 are two separate objects in memory.

If you want to test if two lists have the same elements, you can use the == operator:

list1 = [6,7,8]
list2 = [6,7,8]
print(list1 == list2)

This will output True , indicating that the two lists have the same elements.
I hope it helps. Happy Learning :blush:

3 Likes