I have a nested list A
. I then let list B=list A
. When I try to edit list B by changing some of its elements using B[1][2]=2
, list A[1][2]
gets changed too.
Why would this happen?
Because you are assigning a reference, so list B is actually pointing to list A. You would have to use copy of list. answered here:
Try this:
A = [[1,2,3],[4,5,6],[1,2,3,4]]
B = []
for i in range(len(A)):
c = list(A[i])
B.append(c)
Then you will be able to change B without changing A.
instead of:
listB = listA
try:
listB = listA[:]
And here's an excellent explanation for why this happens:
http://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/
Edit explain whole though process…:
list = [[],[],[],[]]
a = 0
b = 3
list[a] = [1,2,3]
list[b] = list[a][:]
now list[b]
is a copy and not the same list as list[a]
and you cant edit them independently.