pythonadvanced10 minutes

Predict Output of Recursive Python Function with Mutable Default Arguments

Analyze the output of an advanced recursive Python function that uses mutable default arguments and in-place list modifications to understand how state is preserved and mutated across recursive calls.

Challenge prompt

Consider the following Python function that recursively modifies a list passed via a mutable default argument and uses conditional logic to build a result. Predict the exact output when the function is called without arguments. What will be printed after executing main()? Analyze the recursion, list mutations, and order of execution carefully.

Guidance

  • Trace the recursive calls step-by-step, keeping track of how the list 'acc' changes each time.
  • Remember that default arguments are evaluated once when the function is defined, not each time it is called.
  • Pay close attention to the base case and the order in which the recursive calls append to the list.

Hints

  • Mutable default arguments retain changes between function calls.
  • Each recursive call modifies the same list instance passed down, leading to an accumulation of elements.
  • Consider the recursion unwinding phase and how elements are appended during that phase.

Starter code

def recursive_accumulate(n, acc=[]):
    if n == 0:
        acc.append('base')
        return acc
    acc.append(n)
    recursive_accumulate(n-1, acc)
    acc.append(-n)
    return acc

def main():
    result = recursive_accumulate(3)
    print(result)

main()

Expected output

['3', '2', '1', 'base', '-1', '-2', '-3'] (Note: Output will actually be [3, 2, 1, 'base', -1, -2, -3])

Core concepts

recursionmutable default argumentslist mutationorder of operations

Challenge a Friend

Send this duel to someone else and see if they can solve it.