Python Practice Question 1: Mutable Default Argument
Python · Test 1 · question 1 of 10
A helper is defined as def f(x, acc=[]): acc.append(x); return acc and then called with print(f(1), f(2)) in a fresh interpreter. What does the print call output?
Show answer and explanation
Answer:
Default values are evaluated exactly once, when the def statement runs, not on every call. Both calls that omit acc therefore receive the same list object. f(1) appends 1 to it and returns it; f(2) appends 2 to that same list and returns it again. Both arguments to print are references to one list, and by the time print formats them the list is [1, 2], so it prints [1, 2] [1, 2].
Option B is what people expect if they assume a fresh list per call. That is not how defaults work, which is why the idiom is acc=None plus if acc is None: acc = [] inside the body.
Option C is the most tempting wrong answer: it assumes the first result was "snapshotted" as [1] before the second call ran. But f(1) returned the list object itself, not a copy, and the second call mutated that same object before print ran.
Option D is wrong: any expression, including a mutable list, is allowed as a default value. Python does not reject it; it simply shares it between calls.
Reference: Programming FAQ: Why are default values shared between objects?