If I want to generate a list of 0s of length 5, I can do something like
lst = [0] * 5
But if I try to extend this to a 5x5 grid by doing
grid = [[0] * 5] * 5
Something weird seems to happen. I'm not able to change individual cells in the grid. Doing grid[0][0] = 1
, I would expect this output:
[[1, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
Instead, this is what I get:
[[1, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[1, 0, 0, 0, 0]]
I'm able to overcome this by using grid = [[0] * 5 for _ in range(5)]
, but why does the original method not work? It seems like each row is an alias of each other row. Why?