Sub topic 11
Turning Tail Recursion into a Loop
This chapter assumes you can write Python functions and while loops. It also assumes you have read the earlier chapters on accumulators and on tail calls. You should know what a tail call is, and you should know that CPython does not optimize tail calls. Here you will learn a mechanical recipe for rewriting a tail-recursive function as a loop. You will also learn the mistakes people make when they apply it.
Why the Conversion Works
A tail call is the last thing a function does. After the recursive call returns, the caller has no work left. It just passes the result back up. This means the caller's stack frame holds nothing that will ever be needed again.
A language with tail-call optimization reuses that frame. Python does not, so each call adds a frame until the depth limit stops you. You can do the frame reuse by hand. Store the parameters in variables, overwrite them with the new argument values, and jump back to the top of the function. In Python, a loop is how you jump back to the top.
The parameters of the recursive function become the loop variables. The recursive call becomes an update of those variables. The base case becomes the loop's exit.
The Recipe
| Recursive form | Loop form |
|---|---|
| Function parameters | Loop variables, initialized from the arguments |
| Base case test | Loop exit condition (the `while` test is its negation) |
| Base case return value | The `return` after, or inside, the loop |
| `return f(new_args)` | Assign `new_args` to the variables, then repeat |
| Default accumulator value | Initial value of the accumulator variable |
Apply it in four steps:
- Confirm that every recursive call is in tail position. If one is not, first rewrite the function with an accumulator.
- Turn the parameters into local variables. Default parameter values become their starting values.
- Wrap the body in a loop. Keep the base case as the exit.
- Replace each
return f(x2, y2)with a single simultaneous assignmentx, y = x2, y2.
A Worked Example: Summing 1 to n
Here is the tail-recursive sum from the accumulator chapter, next to its loop form.
def sum_to_tail(n, acc=0):
if n == 0:
return acc
return sum_to_tail(n - 1, acc + n)
def sum_to_loop(n):
acc = 0
while n != 0:
acc = acc + n
n = n - 1
return acc
print(sum_to_tail(100)) # 5050
print(sum_to_loop(100)) # 5050Each part maps across:
- The default
acc=0becomesacc = 0before the loop. - The base case
n == 0becomes the loop conditionn != 0. The loop runs while the base case is false. - The base case result
accis what the loop returns after it exits. - The call
sum_to_tail(n - 1, acc + n)becomes the two updates in the loop body.
This version updates acc before n, and the order matters. The new acc uses the old n. If you decrement n first, you add the wrong values. The safest habit is to update everything in one statement: acc, n = acc + n, n - 1. Python evaluates the whole right side before it assigns anything, which matches how the arguments of a function call work.
The difference shows up at depth. sum_to_tail(5000) raises RecursionError with the default limit of about 1000. sum_to_loop(5000) returns 12502500 and uses constant stack space.
The Generic Shape: `while True`
The neat while condition: form is not always easy to see at first. A shape that always works is while True: with the original body inside it. Keep every return that is not a recursive call. Change each recursive return into an assignment. When the loop body ends, control goes back to the top. That is the jump.
Binary search shows why this helps. It has two base cases and two different recursive calls.
def bsearch_rec(xs, target, lo, hi):
if lo > hi:
return -1
mid = (lo + hi) // 2
if xs[mid] == target:
return mid
if xs[mid] < target:
return bsearch_rec(xs, target, mid + 1, hi)
return bsearch_rec(xs, target, lo, mid - 1)
def bsearch_mechanical(xs, target, lo, hi):
while True:
if lo > hi:
return -1
mid = (lo + hi) // 2
if xs[mid] == target:
return mid
if xs[mid] < target:
lo, hi = mid + 1, hi
else:
lo, hi = lo, mid - 1
def bsearch_loop(xs, target):
lo, hi = 0, len(xs) - 1
while lo <= hi:
mid = (lo + hi) // 2
if xs[mid] == target:
return mid
if xs[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
data = [1, 3, 5, 7, 9, 11]
print(bsearch_rec(data, 7, 0, len(data) - 1)) # 3
print(bsearch_mechanical(data, 7, 0, len(data) - 1)) # 3
print(bsearch_loop(data, 4)) # -1The two branches do not need two loops. Each branch updates the variables in its own way, and both go back to the same test. The arguments that stay the same, xs and target, need no update. After the mechanical version works, you can tidy it. Lift a base case into the while condition, drop the no-op assignments such as hi = hi, and hide the starting values behind a simpler signature.
The Most Common Bug: Sequential Updates
Euclid's algorithm for the greatest common divisor is tail recursive:
def gcd_rec(a, b):
if b == 0:
return a
return gcd_rec(b, a % b)
def gcd_loop(a, b):
while b != 0:
a, b = b, a % b
return a
def gcd_broken(a, b):
while b != 0:
a = b
b = a % b # uses the NEW a, which equals b, so b becomes 0
return a
print(gcd_rec(48, 18)) # 6
print(gcd_loop(48, 18)) # 6
print(gcd_broken(48, 18)) # 18, which is wrongIn the recursive call, b and a % b are both computed from the old values. gcd_broken overwrites a before it computes a % b, so b becomes b % b, which is 0. Use tuple assignment, or compute the new values into temporary variables first.
Calls That Look Like Tail Calls but Are Not
The recipe only works when the call is truly the last thing the function does. Watch for these cases:
return 1 + f(n - 1)is not a tail call. The addition happens afterfreturns. Add an accumulator first.return f(n - 1) * nis not a tail call either, for the same reason.return f(x)inside atryblock that has afinally, or inside awithblock, is not a tail call. The cleanup code runs after the call returns.return g(x), wheregis a different function, is a tail call. It does not loop back to the same body, though. Converting mutual recursion needs a state variable that records which function you are "in". The mutual recursion chapter covers this.
When you add an accumulator to remove pending work, check that the combining operation lets you change the order of evaluation. Addition and multiplication are associative, so you can move the work into the accumulator safely. For operations like list concatenation, order matters. acc + [x] and [x] + acc give different lists, so pick the one that keeps the original order.
Checking That the Conversion Is Correct
The two forms should agree on every input where the recursive one finishes. A short brute-force check catches most mistakes:
def sum_to_tail(n, acc=0):
if n == 0:
return acc
return sum_to_tail(n - 1, acc + n)
def sum_to_loop(n):
acc = 0
while n != 0:
acc, n = acc + n, n - 1
return acc
for n in range(0, 500):
assert sum_to_tail(n) == sum_to_loop(n), n
print("all match")
print(sum_to_loop(1_000_000)) # 500000500000, far deeper than recursion allowsTest the edge inputs as well, such as zero, empty lists, and the smallest valid value. Both versions should also fail in the same way on bad input. For example, sum_to_tail(-1) recurses until it raises RecursionError, and sum_to_loop(-1) loops forever. These failures are different. If negative input is possible, add a guard such as while n > 0 or raise a ValueError before the loop starts.
Exercises
Exercise
Convert this tail-recursive function to a loop using simultaneous assignment: def power(base, exp, acc=1): if exp == 0: return acc; return power(base, exp - 1, acc * base)
Show answer
def power_loop(base, exp): acc = 1; while exp != 0: acc, exp = acc * base, exp - 1; return acc. The default acc=1 becomes the starting value. The base case exp == 0 becomes the exit condition. The tail call becomes one tuple assignment. base never changes, so it needs no update.
Exercise
A student converts def countdigits(n, acc=1): if n < 10: return acc; return countdigits(n // 10, acc + 1) into a loop that starts with acc = 1 and uses while n < 10: n = n // 10; acc = acc + 1, then returns acc. What is wrong?
Show answer
The loop condition is the base case itself, but it should be the negation of the base case. The correct loop is while n >= 10. With the bug, countdigitsloop(12345) never enters the loop and returns 1, and a one-digit input such as 5 never stops looping, because 0 // 10 is 0 and stays below 10.
Exercise
Why can you not apply the recipe directly to def length(xs): if not xs: return 0; return 1 + length(xs[1:]), and what would you do first?
Show answer
The recursive call is not in tail position, because 1 + is applied after it returns. First add an accumulator: def length(xs, acc=0): if not xs: return acc; return length(xs[1:], acc + 1). Then convert it: acc = 0; while xs: xs, acc = xs[1:], acc + 1; return acc. A better loop walks an index rather than slicing, because each slice copies the list.