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.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Hard
- Time target: 105 seconds
Question
What does this Python program print?
a = [[0] * 3] * 2
a[0][0] = 7
print(a)Options
- [[7, 0, 0], [0, 0, 0]]
- [[7, 0, 0], [7, 0, 0]]
- [[7, 7, 7], [0, 0, 0]]
- [[7, 0, 0]]
Show the answer and the worked solution
Correct answer: B. [[7, 0, 0], [7, 0, 0]]
Worked solution
- [0] * 3 builds one inner list [0, 0, 0]; multiplying the outer list by 2 stores that same object twice.
- There is only one inner list, so writing a[0][0] = 7 is visible through both rows.
- 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