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
- Draw every assignment as an arrow from a name to an object; b = a adds an arrow, not an object.
- Apply each mutation to the object at the end of the arrow β every name pointing there sees it.
- Distinguish rebinding from mutating: b = b + [4] creates a new object for b; b += [4] mutates the shared one.
- Check copies for depth: a[:] separates the outer list only; inner lists still shared.
Common wrong fixes
- Reading b = a as 'b gets a snapshot of a's current contents'.
- Believing += and + assignment behave identically for lists β one mutates, the other rebinds.
- Using copy() and being surprised that modifying a nested element still leaks through (shallow vs deep).
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.
π¦ Learning path: Lists and Dictionaries
Problem 6 of 20 in this path. Work them in order β each one builds on the rule before it.
πΌ 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
- Output-prediction strategies β how to predict tricky snippets without running them.
- Browse every lists problem in this topic.
- Common Python errors and what they actually mean, plus the Python glossary for any term used on this page.