Data Structures & AlgorithmsHardProduct placement · Amazon/Microsoft

A Python 2-D list is created two ways and one cell is set. What is printed?

A Python 2-D list is created two ways and one cell is set. What is printed?
a = [[0] * 3] * 3
b = [[0] * 3 for _ in range(3)]
a[0][0] = 5
b[0][0] = 5
print(sum(map(sum, a)), sum(map(sum, b)))
  1. A. 15 4
  2. B. 15 6
  3. C. 5 5
  4. D. 15 5

Correct answer: D. 15 5

[[0] * 3] * 3 repeats a reference to ONE inner list, so a single assignment changes all three rows; the comprehension builds independent rows. Output: 15 5.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic