Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append list to list, overwrite values

I want append to list1, another list2, so modify the list2 and another time append to list1, but the values of list1 are overwrite.

I used [:] with the append and works ok:

list1=[1,2]
list2=[]

list2.append(list1[:])

list1[0]=20

print list1, list2 # [20, 2] [[1, 2]]

But the problem is when the list has another list inside

list1=[[2,1],[2]] 
list2=[]

list2.append(list1[:])

print list1, list2  #[[2, 1], [2]] [[[2, 1], [2]]]

list1[0][0]=25

list2.append(list1)

print list1, list2  #[[25, 1], [2]] [[[**25**, 1], [2]], [[25, 1], [2]]]

I want to be that the last print was [[25, 1], [2]] [[[2, 1], [2]], [[25, 1], [2]]]

like image 362
Jose Brotons Pla Avatar asked May 23 '26 18:05

Jose Brotons Pla


1 Answers

I think what you're asking is:

from copy import deepcopy
list1.append(deepcopy(list2))
like image 134
Jon Clements Avatar answered May 26 '26 08:05

Jon Clements



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!