Sub topic 8
Recursion Versus Iteration
This chapter assumes you can read Python functions, loops, and list slicing. It also assumes you have met the call stack and the recursive list functions from the previous chapters. Here we put a recursive solution next to a loop that does the same job, then compare what each one costs and when each one fits.
The Same Problem, Two Ways
In the last chapter you summed a list recursively by splitting it into a first element and a smaller remainder:
def total(items):
if not items:
return 0
return items[0] + total(items[1:])
def total_iterative(items):
result = 0
for x in items:
result += x
return result
print(total([3, 1, 4])) # 8
print(total_iterative([3, 1, 4])) # 8Both functions return the same answer, but they keep track of their progress in different places.
- The recursive version keeps its pending work on the call stack. Each frame holds one
items[0]and waits for the deeper call to return before it can add. - The iterative version keeps its progress in one variable,
result. The loop updatesresultin place, and no work waits to be finished later.
Any recursive function can be rewritten as a loop, and any loop can be rewritten as recursion. The question is which form is clearer and cheaper for a given problem.
Comparing the Costs
Stack space
The recursive total makes one call per element, plus one for the empty list. A list of length n needs n + 1 frames on the stack at the deepest point, so it uses O(n) stack space. The loop uses O(1) extra space no matter how long the list is.
This matters in practice. CPython limits how deep the call chain can go, so total fails on a list of a few thousand elements while total_iterative handles millions. A later chapter covers that limit in detail.
Hidden copying
The slice items[1:] builds a new list each time. Slicing a list of length k copies k − 1 elements, so the recursive total does about n + (n − 1) + ... + 1 copies, which is O(n²) time. The loop is O(n).
Pass an index instead of slicing to remove the copying:
def total_from(items, i=0):
if i == len(items):
return 0
return items[i] + total_from(items, i + 1)
print(total_from([3, 1, 4])) # 8This version runs in O(n) time. It still uses O(n) stack space, because one frame per element is still waiting to add.
Call overhead
In Python, a function call costs more than a loop iteration. The interpreter has to create a frame, bind the arguments, and clean up afterward. You can measure the difference:
import timeit
def total_from(items, i=0):
if i == len(items):
return 0
return items[i] + total_from(items, i + 1)
def total_iterative(items):
result = 0
for x in items:
result += x
return result
data = list(range(500))
print("recursive:", timeit.timeit(lambda: total_from(data), number=2000))
print("iterative:", timeit.timeit(lambda: total_iterative(data), number=2000))On a typical machine the recursive version takes several times longer. The exact ratio depends on the Python version and the hardware, so measure before you treat it as decisive.
Summary of costs
| Version | Time | Extra stack space | Fails on very long input? |
|---|---|---|---|
| `total` (slicing) | O(n²) | O(n) | Yes |
| `total_from` (index) | O(n) | O(n) | Yes |
| `total_iterative` | O(n) | O(1) | No |
When Recursion Is the Better Choice
The costs above make recursion look like a bad deal for lists. For a straight sequence it often is: a loop matches the shape of the problem, so the loop is just as clear and cheaper to run.
Recursion pays off when the problem has a branching or nested shape:
- Trees and nested data. A folder can contain folders, and a JSON value can contain lists of objects that contain lists. Recursive code follows the structure directly, while a loop has to manage its own stack by hand.
- Divide and conquer. Merge sort splits a list in two and sorts each half. Recursion expresses this in a few lines, and the depth is only about log₂ n, so the stack limit rarely matters.
- Search with undo. Backtracking makes a choice, explores it, and undoes it. The call stack remembers each choice for you.
- Definitions that are already recursive. Factorial, Fibonacci, and grammar rules are defined in terms of themselves, so the code can mirror the definition and be checked against it line by line.
The deciding factor is often the recursion depth, not the input size. A balanced tree with a million nodes is only about 20 levels deep. A linked list with a million nodes is a million levels deep.
Converting Between the Two
Some recursive functions convert to loops easily. When each call does its work before the recursive call and passes the running result forward, the state fits in a few variables:
def reverse(s):
if len(s) <= 1:
return s
return reverse(s[1:]) + s[0]
def reverse_iterative(s):
result = ""
for ch in s:
result = ch + result
return result
print(reverse("abc")) # cba
print(reverse_iterative("abc")) # cbaHere the loop variable result stores what the stack frames stored in the recursive version: the reversed text built up so far. (For real code, s[::-1] is the idiomatic way to reverse a string in Python.)
Functions that make more than one recursive call, such as a tree walk, are harder to convert. Each pending branch has to be remembered somewhere, so the loop needs its own list that acts as a stack. A later chapter shows that technique.
Common Errors
- Assuming recursion is always slower or always more elegant. It depends on the problem's shape and the language. Measure before optimizing.
- Ignoring depth. Code that passes tests on 10 elements can crash on 10,000. Estimate the maximum depth for realistic inputs.
- Hidden O(n²) from slicing or string concatenation in each call.
- Writing a loop that copies the recursive version's bugs. If the base case was wrong in the recursive version, the loop's starting value will usually be wrong in the same way. Check the empty input in both versions.
Exercise
Write an iterative function counteven(items) that returns how many numbers in items are even, and a recursive version counteven_rec(items, i=0) that uses an index instead of slicing. What is the extra stack space of each?
Show answer
Iterative: count = 0; for x in items: if x % 2 == 0: count += 1; return count. Recursive: if i == len(items): return 0; return (1 if items[i] % 2 == 0 else 0) + countevenrec(items, i + 1). The iterative version uses O(1) extra space. The recursive version uses O(n) stack space, one frame per element plus one for the base case.
Exercise
You must process a directory tree that is at most 15 levels deep but contains 200,000 files. Would you choose recursion or iteration, and why?
Show answer
Recursion is a reasonable choice. The stack depth depends on how deeply the folders nest (15 levels), not on the number of files, so it stays far below the recursion limit. The recursive code also follows the nested structure of the tree directly.
Exercise
Why does total(items) with items[1:] take O(n²) time even though it makes only n + 1 calls?
Show answer
Each call copies the remainder of the list when it slices. The copies have lengths n − 1, n − 2, ..., 0, which add up to about n²/2 element copies, so the total time is O(n²).