Sub topic 17
Tail Recursion and Tail-Call Optimization
This chapter assumes you know how the call stack stores one frame per active call. It also assumes you have seen the RecursionError that CPython raises when recursion runs too deep. Here you will learn a form of recursion that some languages can run without growing the stack, and what that means in Python.
What Makes a Call a Tail Call
A call is in tail position when it is the last thing the function does. Its result is returned directly, with no further work. A function is tail recursive when every one of its recursive calls is in tail position.
The usual factorial is not tail recursive:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120After factorial(n - 1) returns, the frame still has to multiply the result by n. That pending multiplication is why every frame must stay on the stack until the deeper calls finish.
The Accumulator Pattern
To make the function tail recursive, carry the partial result forward in an extra parameter called an accumulator:
def factorial_acc(n, acc=1):
if n == 0:
return acc
return factorial_acc(n - 1, acc * n)
print(factorial_acc(5)) # 120The multiplication now happens before the call. When the recursive call returns, the current frame has nothing left to do, so its local variables are no longer needed.
Tail-Call Optimization
Tail-call optimization (TCO) is a compiler or interpreter technique that takes advantage of this. When a call is in tail position, the runtime reuses the current frame instead of pushing a new one. Scheme requires this behavior by its language standard, so a tail-recursive loop there runs in constant stack space.
import sys
def factorial_acc(n, acc=1):
if n == 0:
return acc
return factorial_acc(n - 1, acc * n)
print(sys.getrecursionlimit()) # often 1000
try:
factorial_acc(5000)
except RecursionError:
print("RecursionError")Why It Still Matters in Python
A tail-recursive function converts to a loop mechanically. The parameters become loop variables, the base case becomes the loop's exit condition, and the tail call becomes a reassignment of the parameters:
def factorial_loop(n):
acc = 1
while n != 0:
acc = acc * n
n = n - 1
return acc
print(factorial_loop(5)) # 120
print(len(str(factorial_loop(5000)))) # 16326 digits, no RecursionErrorIn Python, use the accumulator form as a stepping stone. Once the recursion is in tail form, rewrite it as a while loop.
Common Mistakes
| Mistake | Why it fails |
|---|---|
| `return 1 + f(n - 1)` treated as a tail call | The addition runs after the call returns |
| Expecting Python to optimize tail calls | CPython keeps every frame |
| Forgetting to return the accumulator in the base case | The base case returns a constant and the accumulated work is lost |
Exercise
Is return 1 + depth(n - 1) tail recursive? Rewrite depth(n), which returns n for any n >= 0, in tail-recursive form, then as a loop.
Show answer
No. The addition happens after the call returns. Tail form: def depth(n, acc=0): return acc if n == 0 else depth(n - 1, acc + 1). Loop form: def depth(n): then acc = 0, while n != 0: acc += 1; n -= 1, and finally return acc.
Exercise
Write a tail-recursive total(items, acc=0) that sums a list using an index instead of slicing.
Show answer
def total(items, i=0, acc=0): return acc if i == len(items) else total(items, i + 1, acc + items[i]). The recursive call is the last action, so the function is tail recursive. In CPython it is still limited by the recursion depth.