Data Structures & AlgorithmsHardTCS NQT Digital · Python semantics

Problem: What does the following print?

Problem: What does the following print?
x = [[0] * 2] * 2
x[0][1] = 5
print(x)
  1. A. [[0, 5], [0, 5]]
  2. B. [[0, 5], [0, 0]]
  3. C. [[0, 0], [0, 5]]
  4. D. [[5, 5], [0, 0]]

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

[[0] * 2] * 2 repeats one inner list twice, so both rows are the same object and the write shows in both. Building the rows with a comprehension avoids this aliasing.

More Coding Interview Problems questions

Exams that ask this topic