How lists are saved in memory

list1 = [] 
list2 = [] 
list3 = list1

print(list1 is list3)

Explain how list1 and list3 is stored in memory?

Below image shows how variables are saved in memory based on a given code operation


When we do

list3 = list1

You can see that the original memory location A for list 1 is modified

But when we do

list2 = []

You can see that a new memory location is created.

Now i think your question is exactly why a new memory location is created for list2 = [] when we already have a empty list memory location defined.

So the answer to that is

let’s suppose you modify list2 to include a new element. (since lists are mutable so it is allowed that we can change the elements of lists)

list2.append(1)

This operation will change the value of list2. But should this operation change the value of list1 as well. No it should not and for ensuring this we tried to define list2 as a new empty list. (that was the motive of defining a new empty list so that any changes we do here does not change list1)

If we would have wanted to change list1 we could change list3 and that would change list1.

2 Likes

I just want to add some points to this conversation.

CASE -1


l1=[1,2,3]
l2=[4,5,6]
l3=l1
l1.append(9)
print(l1 == l3)
print("l1 = ",l1)
print("l3 = ",l3)

It is the following output:

output :

True
l1 =  [1, 2, 3, 9]
l3 =  [1, 2, 3, 9]

Since I directly assigned l1 to l3 ( l1 == l2 ) it gives true as they are pointing to the same memory location. If I change the values in one list modifies the other one.

CASE -2

l1=[1,2,3]
l2=[4,5,6]
l3=l1.copy()
l1.append(9)
print(l1 == l3)
print("l1 = ",l1)
print("l3 = ",l3)

when I used the copy() keyword present in python it gives the following output.

output :

False
l1 =  [1, 2, 3, 9]
l3 =  [1, 2, 3]
3 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.