Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Edge case: building a 3 × 3 grid with list multiplication.

Edge case: building a 3 × 3 grid with list multiplication.
grid = [[0] * 3] * 3
grid[0][0] = 1
print(grid)
What is printed?
  1. A. [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
  2. B. [[1, 1, 1], [0, 0, 0], [0, 0, 0]]
  3. C. It raises a TypeError
  4. D. [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

Correct answer: D. [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

[[0] * 3] * 3 repeats a reference to the SAME inner list three times, so changing grid[0][0] changes every row. Build rows independently with [[0] * 3 for _ in range(3)].

More Coding Interview Problems questions

Exams that ask this topic