ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

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

Correct answer: C. [0, 0, 0] [[0, 7], [0, 7]]

[[0] * 2] * 2 repeats one inner list object, so both rows are the same object and changing one changes the other. Use [[0] * 2 for _ in range(2)] for independent rows.

More Python Programming questions

Exams that ask this topic