1
Matrix = [[0]*3]*3
matrix[0][0] = 1

the result is [[1,0,0],[1,0,0],[1,0,0]] what's the issue here? is this a bug for matrix in Python?

JamesWang
  • 1,175
  • 3
  • 14
  • 32

1 Answers1

1

Because all the indices in your matrix point to the same list (namely [0]*3). You should create a new list for each index:

matrix = [[0]*3 for i in range(3)]
matrix[0][0] = 1

print(matrix)
# [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
slider
  • 12,810
  • 1
  • 26
  • 42
  • Thanks for replying. I'm still confused and what do you mean "all the indices in your matrix point to the same list (namely [0]*3)"? – JamesWang Nov 23 '18 at 22:17
  • The way I used should create a 2d matrix 3x3, so I think matrix[0][0] should be the one at the first row and first column, it's one element in this 2d matrix, but how come the assignment to this one element changes all values in the first column? – JamesWang Nov 23 '18 at 22:20
  • @JamesWang Perhaps the picture here should explain it better: https://stackoverflow.com/a/18454568/1822698 Let us call the list `[0]*3` as `lst`. With your approach, you are only creating *one* `lst` and `matrix[0]`, `matrix[1]`, and `matrix[2]` are all pointing to that one `lst`. Therefore, if you change `matrix[0][0]`, it changes `lst[0]`. But `matrix[1]` is also pointing to `lst`. So `matrix[1][0]` also reflects that change. Does that make sense? – slider Nov 23 '18 at 23:59
  • 1
    Makes sense to me now! Thanks @slider – JamesWang Nov 24 '18 at 03:54