ProgrammingHardTCS NQT · Infosys

What is printed?

What is printed?
x = [0] * 3
x[0] += 1
y = [[0]] * 2
y[0][0] += 1
print(x, y)
  1. A. [1, 0, 0] [[0], [0]]
  2. B. [0, 0, 0] [[1], [1]]
  3. C. [1, 1, 1] [[1], [1]]
  4. D. [1, 0, 0] [[1], [1]]

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

[0] * 3 makes three separate ints, so only the first one changes. [[0]] * 2 repeats one inner list twice, so the update to y[0][0] shows through both references.

More Python Programming questions

Exams that ask this topic