ProgrammingHardWipro NLTH · Python

What is printed?

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

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

[[0]*2]*2 repeats a reference to one inner list, so both rows change; the comprehension builds two independent rows.

More Python Programming questions

Exams that ask this topic