ProgrammingHardPython · GATE DA · Advanced

What is printed?

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

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

[a] * 2 repeats a reference to the same list, so one write shows in both rows and in a; the comprehension builds distinct rows.

More Python Programming questions

Exams that ask this topic