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?
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With