← Back

Home β€Ί Problems β€Ί List copy vs reference

List copy vs reference

🧠 Predict the output Topic: lists Difficulty: easy 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: easy β€” the fix or the trick is normally a single line, and a careful read should be enough.

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:

original = [1, 2, 3]
copy = original.copy()
copy.append(4)
print(original)
print(copy)

Understand the rule

b = a does not copy a list β€” it makes b a second name for the same object, so a.append() shows up in b and vice versa. A real copy needs list(a), a[:], or a.copy(), and even those are shallow: nested lists inside remain shared. Most 'impossible' output predictions in this area dissolve once you draw the objects and the names pointing at them.

How to trace it

  1. Draw every assignment as an arrow from a name to an object; b = a adds an arrow, not an object.
  2. Apply each mutation to the object at the end of the arrow β€” every name pointing there sees it.
  3. Distinguish rebinding from mutating: b = b + [4] creates a new object for b; b += [4] mutates the shared one.
  4. Check copies for depth: a[:] separates the outer list only; inner lists still shared.

Common wrong fixes

Rule to remember

Assignment shares; slicing/list()/copy() copy one level; deepcopy() copies all levels. When two variables change 'mysteriously' together, they are two names for one object.

Solve it in the interactive editor β†’

πŸ“¦ Learning path: Lists and Dictionaries

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

← Previous problemNext in path: List multiplication β†’

πŸ’Ό Learning path: Interview Practice

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

← Class variable shared across instancesNext in path: List multiplication β†’

More lists problems

Keep going