AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Hardpythonlistsaliasing

~105s

Building a grid with the repetition operator

What does this Python program print?

a = [[0] * 3] * 2
a[0][0] = 7
print(a)
Show the answer and the worked solution

Correct answer: B.

[[7, 0, 0], [7, 0, 0]]

Worked solution

  1. [0] * 3 builds one inner list [0, 0, 0]; multiplying the outer list by 2 stores that same object twice.
  2. There is only one inner list, so writing a[0][0] = 7 is visible through both rows.
  3. The printed value is [[7, 0, 0], [7, 0, 0]].

Answer: [[7, 0, 0], [7, 0, 0]].

The idea

The repetition operator duplicates references, which is harmless for immutable elements and treacherous for lists. A comprehension such as [[0] * 3 for _ in range(2)] builds genuinely separate rows.

Shortcut. Count the objects: [0] * 3 runs once, so there is one inner list with two references to it; one write, two rows showing it.

Common trap. "[[7, 0, 0], [0, 0, 0]]" assumes * 2 builds two independent rows, as a comprehension would.

Building a grid with the repetition operator — Aptitude

Building a grid with the repetition operator: What does this Python program print? Answer and worked solution on CodeKairo.

Question

What does this Python program print?

a = [[0] * 3] * 2
a[0][0] = 7
print(a)

Options

  1. [[7, 0, 0], [0, 0, 0]]
  2. [[7, 0, 0], [7, 0, 0]]
  3. [[7, 7, 7], [0, 0, 0]]
  4. [[7, 0, 0]]
Show the answer and the worked solution

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

Worked solution

  1. [0] * 3 builds one inner list [0, 0, 0]; multiplying the outer list by 2 stores that same object twice.
  2. There is only one inner list, so writing a[0][0] = 7 is visible through both rows.
  3. The printed value is [[7, 0, 0], [7, 0, 0]].

Answer: [[7, 0, 0], [7, 0, 0]].

The idea

The repetition operator duplicates references, which is harmless for immutable elements and treacherous for lists. A comprehension such as [[0] * 3 for _ in range(2)] builds genuinely separate rows.

Shortcut. Count the objects: [0] * 3 runs once, so there is one inner list with two references to it; one write, two rows showing it.

Common trap. "[[7, 0, 0], [0, 0, 0]]" assumes * 2 builds two independent rows, as a comprehension would.

All Programming Fundamentals questions · placement mock tests