Reputation: 3
there is a list, after looping, it changes. But I do nothing to change it, just use it.
a = [[1,1,1,1], [0,0,1,1], [1,1,0,0], [0,0,0,0]]
b = a[:]
for i in range(4):
for j in range(4):
b[i][j] = a[j][i]
then a becomes [[1, 0, 1, 0], [0, 0, 1, 0], [1, 1, 0, 0], [0, 0, 0, 0]]
I really appreciate it if someone tells me what happened and how to fix this problem.
Upvotes: 0
Views: 79
Reputation: 92471
b
is not a deep copy of a
it just holds references to the same arrays a
does. When you alter the children in b
you are altering the same elements in a
.
You don't need to copy the array first. Since you are adding elements to b in order, you can just append as you go:
a = [[1,1,1,1], [0,0,1,1], [1,1,0,0], [0,0,0,0]]
b = []
for i in range(4):
b.append([])
for j in range(4):
b[i].append(a[j][i])
You can also get the same result much simpler with:
a = [[1,1,1,1], [0,0,1,1], [1,1,0,0], [0,0,0,0]]
list(zip(*a))
Upvotes: 1