Questions / Quant development, Python correctness
A default argument remembers
In Python, f(10) is called and then f(20). What does the second call return?
def f(x, values=[]):
values.append(x)
return len(values)
Answer it in the app It's free. You get hints, a second try if you miss, and a follow-up question.
Show the answer and worked solution
Answer: 2 length
- The default list is created when Python executes the function definition. It is reused when the argument is omitted.
- f(10) appends 10 to that list, leaving [10]. f(20) then appends to the same list, leaving [10,20].
- The second call returns len(values)=2. A new local parameter name does not create a fresh underlying list.
Interview shortcut. Defaults evaluate once, at def time; the list is shared.
Takeaway. Trace object lifetime across calls, not only within one call.
In the app this has a follow-up where one thing about the setup changes. Try the follow-up.