Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicating an element of a list back into the list in Python

Copying an element back into the list:

>> a = [[1,2],[3,4]]
>> b = []
>> b = a[1]
>> a.insert(1,b)
>> a
[[1,2],[3,4],[3,4]]
>> a[2][0] = 0
>> a
???

What do you expect list 'a' to be? It comes out to be as [[1,2],[0,4],[0,4]] which was very surprising to me whereas I expected [[1,2],[1,4],[0,4]]

I kind of know the answer but still, the idea is not very clear. Kindly tell in more detail why does this happen and how to get rid of it?

like image 963
Sunal Mittal Avatar asked Jan 04 '23 18:01

Sunal Mittal


1 Answers

b = a[1]
a.insert(1,b)

b is a reference to a[1] so when you modify the reference after inserting it, it appears in both places since it is essentially pointing to the same data.

if you want to avoid such a scenario, use deepcopy

from copy import deepcopy

a = [[1,2],[3,4]]
b = []
b = deepcopy(a[1])
a.insert(1,b)
print(a) # prints [[1, 2], [3, 4], [3, 4]]
a[2][0] = 0
print(a) # prints [[1, 2], [3, 4], [0, 4]]
like image 94
PYA Avatar answered Jan 06 '23 09:01

PYA