Marcus Min
Marcus Min

Reputation: 3

why does a list change after looping

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

Answers (2)

Mark
Mark

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

strupo
strupo

Reputation: 188

I really appreciate it if someone tells me what happened and how to fix this problem.

About fixing this problem: if you want b to be a copy of a, you can use the copy module:

import copy
a = [[1,1,1,1], [0,0,1,1], [1,1,0,0], [0,0,0,0]]
b = copy.deepcopy(a)

Upvotes: 0

Related Questions