- Published on
Define a two-dimensional array
- Authors
- Name
- Gene Zhang
Right way
matrix = [[0] * n for _ in range(m)]
Wrong way
[[0] * n] * m
This will produce unexpected behavior.
It uses the same array m times and hence changing one impacts all rows.
test = [[0] * 3] * 5
test[1][1]=7
print(test)
# [[0, 7, 0], [0, 7, 0], [0, 7, 0], [0, 7, 0], [0, 7, 0]]