Initializing a matrix in Python using "[[0] * x] * y" creates related rows?
The matrix initialization seems to concatenate the rows in such a way that when one row changes, they all change:
>>> grid = [[0]*5]*5
>>> grid
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
>>> grid[2][2] = 1
>>> grid
[[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0]]
How can I avoid this?
+3
Zaz
source
to share
1 answer
grid = [[0]*5 for i in range(5)]
Note: [int] * 5 copies an int 5 times (but when copying an int, you are just copying the value). [list] * 5 copies the link to the same list 5 times. (when you copy a list, you copy the link pointing to the list in memory).
+8
robert king
source
to share