0

I am trying to solve leetcode questions and got stuck on question #2120. Below is the portion of the code that needs to be resolved.

grid1 = [[[0, 0]] * n] * n
for i in range(n):
 for j in range(len(grid1[i])):
  grid1[i][j] = [i, j]
print(grid1)

Below is my output: [[[2, 0], [2, 1], [2, 2]], [[2, 0], [2, 1], [2, 2]], [[2, 0], [2, 1], [2, 2]]]

Why do all the cells have the last i-th value? What is wrong in the code?

I want the output to be: [[[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]], [[2, 0], [2, 1], [2, 2]]]

  • You are assigning multiple references to the same list in grid1 (https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Fractalism Jan 22 '23 at 19:06
  • `grid1 = [ [[row,col] for row in range(n)] for col in range(n) ]` – Alain T. Jan 23 '23 at 06:10

0 Answers0