Questions / Quant development, Python correctness

A default argument remembers

Foundation, about 6 minutes. Question D001.

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

  1. The default list is created when Python executes the function definition. It is reused when the argument is omitted.
  2. f(10) appends 10 to that list, leaving [10]. f(20) then appends to the same list, leaving [10,20].
  3. 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.

More python correctness questions