I followed the two following link to solve my issue: first, second
My script is below:
list0=[[0,1,2],[3,4,5],[5,6,7]]
list2=list(list0)
list2[0][0]=20
print(list0) # displays [[20, 1, 2], [3, 4, 5], [5, 6, 7]]
print(list2) # displays [[20, 1, 2], [3, 4, 5], [5, 6, 7]]
As you can see, modifying my list2 modify as well list0. However I took care to create list2 with the function list(). Shouldn't it create a really new list?
I don't understand why it doesn't work here.
On the other hand, it this other example below it works:
list0=[[0,1,2],[3,4,5],[5,6,7]]
list2=list(list0)
list2[0]=[20,30,40]
print(list0) # prints [[8, 9, 10], [3, 4, 5], [5, 6, 7]]
print(list2) # prints [[20, 30, 40], [3, 4, 5], [5, 6, 7]]: Good !
My questions:
Why it doesn't work in the first example but does in the second? How to make sure to not have this issue and to "really" create a new list such that if I modify this new the old will never be modified, whatever there is in this old list.
Is it because list2 and list0 are pointing toward different elements. Thus modifying list2[i] will not modify list0[i]. However, list2[i] and list0[i] point toward the same list, hence modifying list2[i][j] will modify list0[i][j]? In some way I created different references at some hierarchy but not for all levels?
CodePudding user response:
The problem here is that while list2 = list(list0)
makes it so that the outer list is different between your two instances, all inner lists are still the same. To avoid this you can either use copy.deepcopy
:
from copy import deepcopy
list0 = [[0, 1, 2], [3, 4, 5], [5, 6, 7]]
list2 = deepcopy(list0)
list2[0][0] = 20
print(list0) # [[0, 1, 2], [3, 4, 5], [5, 6, 7]]
print(list2) # [[20, 1, 2], [3, 4, 5], [5, 6, 7]]
or a nested list comprehension:
list0 = [[0, 1, 2], [3, 4, 5], [5, 6, 7]]
list2 = [list(sublist) for sublist in list0]
list2[0][0] = 20
print(list0) # [[0, 1, 2], [3, 4, 5], [5, 6, 7]]
print(list2) # [[20, 1, 2], [3, 4, 5], [5, 6, 7]]
but do note that you'd have to adjust the latter approach if the nesting depth was different.
CodePudding user response:
No, list()
converts it's parameter to a list. Therefore you're having list2
as variable which references list0
. What you're looking for is copy()
.