ProgrammingHardProduct-company MCQ pattern

What is printed on the first line?

What is printed on the first line?
grid = [[0] * 2] * 2
grid[0][0] = 1
print(grid)
g2 = [[0] * 2 for _ in range(2)]
g2[0][0] = 1
print(g2)
  1. A. [[1, 0], [0, 0]]
  2. B. [[1, 1], [0, 0]]
  3. C. [[1, 0], [1, 0]]
  4. D. [[0, 0], [1, 0]]

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

[[0] * 2] * 2 repeats one inner list reference, so changing grid[0][0] changes both rows. A list comprehension builds a fresh inner list on each pass, which is why the second grid changes only row 0.

More Python Programming questions

Exams that ask this topic