0

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?

Param
  • 609
  • 2
  • 5
  • 16
  • 1
    Does this answer your question? [How to define a two-dimensional array?](https://stackoverflow.com/questions/6667201/how-to-define-a-two-dimensional-array) – Ahmed AEK Dec 08 '22 at 06:19
  • @AhmedAEK edited for clarity - I'm more so asking why I get this output using this method – Param Dec 08 '22 at 06:22

1 Answers1

1

let's define this simple 2x1 list the wrong way.

foo = [[0]]*2

this is equivalent to

bar = [0]
foo = [bar, bar]

notice that bar is a multable, so any modification to it will modify both foo[0] and foo[1].

bar = [0]
foo = [bar, bar]
bar[0] = 1
print(foo)

#[[1], [1]]

while the correct way is equivalent to

foo = []
for i in range(5):
    bar = [0]*5
    foo.append(bar)

where each iteration of the loop a new list is created.

Ahmed AEK
  • 8,584
  • 2
  • 7
  • 23