ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

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

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

Multiplying a list of lists copies only the outer reference, so both rows of b are the same list. Building each row with a comprehension gives independent rows.

More Python Programming questions

Exams that ask this topic