0

I want to make a simple array b, and set b[0][0] to be 1. However, b[1][0], b[2][0] and b[3][0] changed as well. How to solve this?

>>> a=[0]*5
>>> b=[a]*4
>>> b
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> b[0][0]
0
>>> b[0][0]=1
>>> b
[[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
ss1234
  • 17
  • 2

1 Answers1

1

List b was created with list a, and all rows in b reference the same list object as a:

You can avoid this behavior by using a copy of a:

b = [a.copy()]

And to avoid each row in b pointing to the same object:

b = [a.copy() for _ in range(4)]
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139