ProgrammingVery hardInfosys HackWithInfy · TCS CodeVita

What is printed?

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

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

[[0]*3]*2 repeats one inner list object, so changing g[0][1] changes both rows. The list comprehension builds separate rows, so only the first row of h changes.

More Python Programming questions

Exams that ask this topic