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?