What is the expected output of the following Python function with a mutable default argument?
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
What is the expected output of the following Python function with a mutable default argument?
def foo(x, l=[]):
l.append(x)
return l
for i in range(3):
y = foo(i)
print(y)
Show answer & explanation
In Python, default mutable arguments (like lists) are evaluated once at function definition time, not each time the function is called. The same list object l=[] is reused across all invocations. Each call appends the new value to the persistent list, resulting in accumulated values: [0], then [0, 1], then [0, 1, 2]. Options B and C assume a fresh list per call (which would require l=None as default with internal initialization), and Option D is incorrect as the code runs without errors.
Step-by-step Derivation:
Execution trace:
- Function definition:
l=[]is created once as a default argument, stored in foo.defaults - i=0: foo(0) → l=[0] (append 0 to the default list) → print([0])
- i=1: foo(1) → l=[0, 1] (append 1 to the SAME list from before) → print([0, 1])
- i=2: foo(2) → l=[0, 1, 2] (append 2 to the same persistent list) → print([0, 1, 2])
This is a classic Python gotcha: mutable default arguments persist across function calls because they are only evaluated once at definition time.