Sub topic 6
Tail Recursion and Accumulator Parameters
This chapter assumes you can read the recursive factorial from earlier chapters and that you know Python raises RecursionError once the call stack gets too deep. You should also be comfortable tracing stack frames by hand.
The plain recursive factorial does its multiplication after the recursive call returns. Every frame has to wait for the frame below it to finish. Tail recursion moves that pending work into a parameter, so each call has nothing left to do once the next call returns.
What Makes a Call a Tail Call
A tail call is a call whose result is returned immediately, with no further work done on it. A function is tail recursive when every recursive call it makes is a tail call.
Compare these two return statements:
| Return statement | Tail call? | Work left after the call |
|---|---|---|
| `return n * factorial(n - 1)` | No | Multiply the result by `n` |
| `return factorial_acc(n - 1, acc * n)` | Yes | None |
In the first statement, the multiplication by n still has to happen after the call returns, so the current frame must stay alive to remember n. In the second, the caller simply passes the callee's answer up unchanged.
The Accumulator Pattern
An accumulator is an extra parameter that carries the partial result down through the calls. Instead of building the answer on the way back up the stack, you build it on the way down.
def factorial_acc(n, acc=1):
if n == 0:
return acc
return factorial_acc(n - 1, acc * n)
print(factorial_acc(5)) # 120The base case changes its meaning. It no longer returns the identity value 1. It returns acc, which by that point already holds the full product.
The trace shows the invariant that makes the function correct: in every call, acc * n! equals 5!. When n reaches 0, that leaves acc = 5!.
Python Does Not Eliminate Tail Calls
Some languages, including Scheme and many functional languages, perform tail call elimination. Because a tail call leaves nothing to do in the current frame, the runtime reuses that frame instead of pushing a new one, so the recursion runs in constant stack space.
CPython does not do this. Each call to factorial_acc still pushes a new frame, so it hits the same depth limit as the plain version:
def factorial_acc(n, acc=1):
if n == 0:
return acc
return factorial_acc(n - 1, acc * n)
try:
factorial_acc(5000)
except RecursionError as e:
print("RecursionError:", e)Converting Tail Recursion to a Loop
A tail-recursive function converts to a loop in three steps:
- Turn the parameters into loop variables, starting at their initial values.
- Turn the base case test into the loop's exit condition, and return the accumulator after the loop.
- Turn the recursive call into one simultaneous reassignment of the variables.
def factorial_loop(n):
acc = 1
while n != 0:
n, acc = n - 1, acc * n
return acc
print(factorial_loop(5)) # 120
print(len(str(factorial_loop(5000)))) # 16326 digits, no RecursionErrorThe tuple assignment matters. Python evaluates the whole right side before assigning anything, so acc * n uses the old value of n, exactly as the recursive call did.
Common Mistakes
- Forgetting to return the accumulator in the base case. Returning
1instead ofaccgives the wrong answer for every input except 0. - Calling a function tail recursive when it is not.
return 1 + count(rest)still has an addition pending after the call. - Updating loop variables one at a time. Writing
n = n - 1and thenacc = acc * nmultiplies by the wrong value.
Exercise
Write a tail-recursive Fibonacci function fib_acc(n, a=0, b=1) that uses two accumulators, then convert it to a loop.
Show answer
Recursive: if n == 0: return a followed by return fib_acc(n - 1, b, a + b). Loop: start with a, b = 0, 1, run while n != 0: n, a, b = n - 1, b, a + b, then return a. Both give fib_acc(10) == 55.
Exercise
Is def total(xs): return 0 if not xs else xs[0] + total(xs[1:]) tail recursive? If not, rewrite it with an accumulator.
Show answer
It is not tail recursive, because the addition xs[0] + ... runs after the recursive call returns. Accumulator version: def total(xs, acc=0): return acc if not xs else total(xs[1:], acc + xs[0]).