← Back

Home β€Ί Problems β€Ί List multiplication

List multiplication

🧠 Predict the output Topic: lists Difficulty: medium Free

What this problem practises

Lists are mutable and assigned by reference. That one fact explains most list bugs: aliasing between what look like "copies", append() and sort() returning None, and slice boundaries that disagree with the index arithmetic.

This is an output-prediction problem: read the snippet carefully and write down exactly what it prints before anything runs. These questions are interview staples because they test whether you know the language rules, or merely recognise their syntax.

Difficulty: medium β€” expect to hold two interacting rules in your head at once, such as a boundary combined with a mutation.

The challenge

The code runs in PyDebug’s in-browser compiler. Open the problem, run the snippet, watch the exact error or output, and keep iterating until it is right. Signed-in solves count toward XP and your daily streak.

The snippet

The interactive editor pre-fills exactly this code β€” read it, then submit your prediction:

row = [0] * 3
print(row)
grid = [row] * 2
grid[0][0] = 9
print(grid)

Understand the rule

[0] * 3 gives [0, 0, 0] β€” handy. [[0]] * 3 gives three references to the same inner list β€” a trap. List multiplication copies references, not objects, so mutating one row of a multiplied nested list changes every row. Predicting this output requires distinguishing flat multiplication (safe, values are copied by reference but numbers are immutable) from nested multiplication (shared mutable rows).

How to trace it

  1. Expand the multiplication: how many elements does the outer list now have?
  2. Ask whether the repeated element is mutable: numbers and strings are safe; inner lists and dicts are shared.
  3. On any mutation like grid[0][0] = 1, apply it to the one shared inner object β€” then read every row through that shared object.
  4. Print with this sharing in mind: all rows show the change.

Common wrong fixes

Rule to remember

List multiplication repeats references. For nested structures, use a comprehension to create fresh inner lists β€” and when output looks 'impossibly' repeated, suspect shared objects.

Solve it in the interactive editor β†’

πŸ“¦ Learning path: Lists and Dictionaries

Problem 7 of 20 in this path. Work them in order β€” each one builds on the rule before it.

← List copy vs referenceNext in path: Next problem β†’

πŸ’Ό Learning path: Interview Practice

Problem 4 of 16 in this path. Work them in order β€” each one builds on the rule before it.

← List copy vs referenceNext in path: Loop variable after the loop ends β†’

More lists problems

Keep going