Sub topic 6
Tail Recursion and Accumulator Parameters
This chapter assumes you have read the earlier chapters on the call stack, recursive factorial, and recursion depth limits. You should be able to trace a recursive call frame by frame and know that CPython raises RecursionError once the stack grows past its limit, which is 1000 frames by default.
Here you will learn a technique for restructuring recursive functions so that the recursive call is the last thing a function does. That shape is called tail recursion. Some languages can run tail-recursive functions in constant stack space. Python is not one of them, and knowing why tells you when the technique is worth using in Python.
What Makes a Call a Tail Call
A tail call is a function call whose result is returned directly, with no more work done after it. A function is tail-recursive when every recursive call it makes is a tail call.
Look again at the factorial from the earlier chapter:
def factorial(n):
if n < 0:
raise ValueError("n must be non-negative")
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120The line return n * factorial(n - 1) looks like it ends with a call, but the call does not happen last. After factorial(n - 1) returns, the current frame still has to multiply the result by n. That multiplication is pending work. Because of it, every frame has to stay on the stack and remember its own n until the call below it finishes.
Some quick checks:
| Return statement | Tail call? | Why |
|---|---|---|
| `return f(n - 1)` | Yes | The result is returned unchanged |
| `return n * f(n - 1)` | No | A multiplication happens after the call |
| `return f(n - 1) + 1` | No | An addition happens after the call |
| `return f(n - 1, acc * n)` | Yes | The work happens before the call, in the arguments |
| `return f(n - 1) if n else 0` | Yes | Whichever branch runs, its value is returned directly |
The fourth row shows the trick this chapter is about. You do the work before the call and pass the partial result along as an argument.
The Accumulator Pattern
An accumulator is an extra parameter that carries the partial result down through the calls. Each call does its share of the work on the accumulator and then passes it on. When the base case is reached, the accumulator already holds the answer, so the base case returns it.
def factorial_acc(n, acc=1):
if n == 0:
return acc
return factorial_acc(n - 1, acc * n)
print(factorial_acc(5)) # 120Here is the trace for factorial_acc(4):
| Call | `n` | `acc` on entry | Next call |
|---|---|---|---|
| 1 | 4 | 1 | `factorial_acc(3, 4)` |
| 2 | 3 | 4 | `factorial_acc(2, 12)` |
| 3 | 2 | 12 | `factorial_acc(1, 24)` |
| 4 | 1 | 24 | `factorial_acc(0, 24)` |
| 5 | 0 | 24 | returns `24` |
On the way back up, no frame does anything except pass 24 along. All of the multiplication happened on the way down. The plain version works the other way: it goes down without computing anything and does every multiplication on the way back up.
The invariant behind the accumulator
The induction chapter showed how to prove a recursive function correct. Accumulator functions are proved with an invariant, which is a statement that holds on entry to every call. For factorial_acc the invariant is:
factorial_acc(n, acc) returns acc * n!
The base case gives acc * 0! = acc, which matches return acc. For the recursive case, assume the invariant holds for n - 1. Then factorial_acc(n - 1, acc * n) returns acc * n * (n - 1)! = acc * n!. The top-level call uses acc = 1, so it returns n!.
When you design an accumulator function, write the invariant first. It tells you what the initial accumulator value must be. That value is the identity of the operation: 1 for multiplication, 0 for addition, "" for string concatenation.
Tail Call Elimination and Why Python Skips It
Once a tail call starts, the calling frame has nothing left to do. A language runtime can therefore reuse that frame for the next call instead of pushing a new one. This is called tail call elimination (TCE), also known as tail call optimization. With TCE, factorial_acc(1_000_000) would use one frame instead of a million.
CPython does not do this. Each call to factorial_acc still pushes a new frame, so the accumulator version hits the same depth limit as the plain one:
def factorial_acc(n, acc=1):
if n == 0:
return acc
return factorial_acc(n - 1, acc * n)
try:
factorial_acc(5000)
except RecursionError:
print("RecursionError: tail recursion did not save any stack space")Python leaves out TCE on purpose. Guido van Rossum's stated reasons are that removing frames would make tracebacks incomplete, which hurts debugging, and that Python programmers should write loops when they need to iterate deeply.
Support varies across languages:
| Language | Tail call behavior |
|---|---|
| Scheme | The standard requires proper tail calls |
| Python (CPython) | No elimination; every call pushes a frame |
| Java | No elimination in the JVM |
| Scala | `@tailrec` makes the compiler turn self-recursion into a loop, or reject the code |
| Kotlin | The `tailrec` modifier compiles self-recursion into a loop |
| JavaScript | ES2015 specifies proper tail calls, but only Safari's engine implements them |
| C / C++ | Optimizing compilers often eliminate tail calls, but the standard does not guarantee it |
Converting Tail Recursion into a Loop
Tail recursion is still useful in Python because it gives you a mechanical path to a loop. A tail-recursive function only rebinds its parameters and jumps back to the top, and that is exactly what a while loop does. The recipe:
- Turn the parameters into local variables with their initial values.
- Turn the base-case test into the loop's exit condition.
- Replace the recursive call with a simultaneous reassignment of all parameters.
- After the loop, return what the base case returned.
def factorial_loop(n):
acc = 1
while n != 0:
n, acc = n - 1, acc * n
return acc
print(factorial_loop(5)) # 120
print(factorial_loop(5000) > 0) # True, no stack growthThe tuple assignment n, acc = n - 1, acc * n matters. Python evaluates the whole right side using the old values before it assigns anything, which matches how arguments are evaluated before a call. If you write two separate lines, n = n - 1 and then acc = acc * n, the second line uses the new n and gives the wrong answer.
Accumulators with More Than One Value
An accumulator can be more than one parameter. Naive Fibonacci makes two recursive calls, so it cannot be tail-recursive as written. If you carry two consecutive Fibonacci numbers, though, you get a single tail call:
def fib_acc(n, a=0, b=1):
if n == 0:
return a
return fib_acc(n - 1, b, a + b)
print(fib_acc(10)) # 55The invariant: if a and b are F(k) and F(k+1), then fib_acc(n, a, b) returns F(k+n). The top-level call starts at k = 0. This runs in linear time. Apply the loop recipe and you get the same a, b = b, a + b loop that the bottom-up Fibonacci chapter builds. An accumulator-passing function is often a loop written as recursion.
Common Errors
Operation order changes
The plain version applies its operations on the way back up, from the base case outward. The accumulator version applies them on the way down, from the outside in. For multiplication and addition the order does not matter, because both are commutative and associative. For string concatenation or list building it does:
def spell(n):
if n == 0:
return ""
return spell(n - 1) + str(n)
def spell_acc_wrong(n, acc=""):
if n == 0:
return acc
return spell_acc_wrong(n - 1, acc + str(n))
def spell_acc(n, acc=""):
if n == 0:
return acc
return spell_acc(n - 1, str(n) + acc)
print(spell(3)) # 123
print(spell_acc_wrong(3)) # 321
print(spell_acc(3)) # 123Check the invariant before you trust the conversion. For spell_acc it is "returns spell(n) + acc", and that tells you to prepend.
Mutable default accumulators
A default such as acc=[] is created once, when the function is defined, and every top-level call shares it. Use None and create a fresh list inside the function:
def evens_up_to(n, acc=None):
if acc is None:
acc = []
if n < 0:
return acc
if n % 2 == 0:
acc.append(n)
return evens_up_to(n - 1, acc)
print(evens_up_to(6)) # [6, 4, 2, 0]
print(evens_up_to(3)) # [2, 0], not polluted by the first callExposing the accumulator to callers
A caller who passes an accumulator argument by mistake gets a wrong answer: factorial_acc(3, 2) returns 12. In library code, hide the accumulator in a private helper and expose a function that takes only n. The same goes for validation. factorial_acc(-1) never reaches n == 0 and runs until it hits RecursionError, so check for negative input once in the public wrapper.
Exercise
Is def count(n): return 0 if n == 0 else 1 + count(n - 1) tail-recursive? If not, rewrite it with an accumulator and state the invariant.
Show answer
It is not tail-recursive, because 1 + ... is pending work after the call. A tail-recursive version is def count(n, acc=0): return acc if n == 0 else count(n - 1, acc + 1). The invariant is that count(n, acc) returns acc + n, so the initial accumulator must be 0.
Exercise
Apply the loop recipe to fib_acc and write the resulting function. Why must the reassignment be a single tuple assignment?
Show answer
def fib_loop(n): a, b = 0, 1; while n != 0: n, a, b = n - 1, b, a + b; return a. With separate assignments, a = b would overwrite a before a + b is computed, so b would become 2 * b instead of the next Fibonacci number.
Exercise
Write a tail-recursive sum_list(xs, i=0, acc=0) that returns the sum of a list, and explain why it still fails for a list of 10,000 numbers in CPython.
Show answer
def sum_list(xs, i=0, acc=0): return acc if i == len(xs) else sum_list(xs, i + 1, acc + xs[i]). It makes one call per element and CPython pushes a new frame for every call, even a tail call. A 10,000-element list goes past the default limit of 1000 frames and raises RecursionError. A loop, or the built-in sum, avoids this.