ProgrammingModerateProduct-company MCQ pattern

What is printed?

What is printed?
x = [[0] * 3] * 2
y = [[0] * 3 for _ in range(2)]
x[0][1] = 5
y[0][1] = 5
print(x, y)
  1. A. [[0, 5, 0], [0, 0, 0]] [[0, 5, 0], [0, 0, 0]]
  2. B. [[0, 5, 0], [0, 5, 0]] [[0, 5, 0], [0, 0, 0]]
  3. C. [[0, 5, 0], [0, 5, 0]] [[0, 5, 0], [0, 5, 0]]
  4. D. [[5, 5, 5], [0, 0, 0]] [[0, 5, 0], [0, 0, 0]]

Correct answer: B. [[0, 5, 0], [0, 5, 0]] [[0, 5, 0], [0, 0, 0]]

Multiplying the outer list copies the REFERENCE to the same inner list twice, so a change through x[0] shows in x[1]. The comprehension builds a new inner list each time. This is the classic 2-D grid bug.

More Python Programming questions

Exams that ask this topic