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]]]
I think what you're asking is:
from copy import deepcopy
list1.append(deepcopy(list2))
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