0

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.

blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Possible duplicate of [Python copy a list of lists](https://stackoverflow.com/questions/28684154/python-copy-a-list-of-lists) – blhsing Apr 05 '19 at 03:49
  • 1
    Possible duplicate of [Copying nested lists in Python](https://stackoverflow.com/questions/2541865/copying-nested-lists-in-python) – Henry Woody Apr 05 '19 at 03:55
  • Does this answer your question? [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – AMC Jan 25 '20 at 22:09

2 Answers2

1

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))
Mark
  • 90,562
  • 7
  • 108
  • 148
0

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)
strupo
  • 188
  • 1
  • 3
  • 14