Sub topic 8
Recursion Versus Iteration
This chapter assumes you can write Python loops, know how the call stack works, and have seen the recursive total function from the chapter on lists and strings. The question here is practical. You can usually write a function either way, so you need to know when each one is the better choice.
The same problem, two ways
Both functions below add up a list. The recursive version treats the list as a first element plus a smaller list. The iterative version walks through the list and keeps a running total.
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])) # 8They return the same results, but they do different work at runtime. total creates one stack frame per element, and each frame waits for the deeper call to return before it can do its addition. total_iterative runs in a single frame and updates one variable. Also, items[1:] copies the rest of the list on every call, so the recursive version takes O(n²) time in total. The loop takes O(n).
How the costs compare
| Aspect | Recursion | Iteration |
|---|---|---|
| State lives in | Stack frames (parameters and locals) | Variables you update |
| Extra memory | One frame per active call | Usually constant |
| Depth risk | Can hit the recursion limit on large inputs | No depth limit |
| Fits naturally | Trees, nested data, divide and conquer | Linear sequences, counting, accumulating |
| Readability | Matches self-similar definitions | Matches step-by-step processes |
Every recursive function can be rewritten as a loop. When the recursion makes only one call per step, as total does, the rewrite is easy. When a function makes several calls per step, as tree walks do, the loop needs its own stack, a technique covered later in this tutorial.
Choosing between them
Here are some common mistakes when choosing:
- Using recursion on a long flat list in Python, where each element adds a frame and large inputs can fail.
- Forcing a loop onto tree-shaped data and ending up managing a hand-built stack that is harder to read than the recursion.
- Assuming recursion is slower in every case. When the input is shallow, the frame overhead rarely matters compared with clear code.
Exercise
Rewrite reverse(s) (which returns reverse(s[1:]) + s[0]) as an iterative function, and state one advantage it has over the recursive version for a 50,000-character string.
Show answer
def reverse_iterative(s): result = ""; then for ch in s: result = ch + result; then return result. In practice, return "".join(reversed(s)) is faster still. The loop runs in a single stack frame, so it cannot raise RecursionError. The recursive version would need about 50,000 nested calls, which is far beyond CPython's default limit of about 1,000.
Exercise
A function walks a nested directory structure that is at most 10 levels deep. Should it be recursive or iterative, and why?
Show answer
Recursive. The data is nested, so the code follows its shape directly, and a depth of 10 is nowhere near the recursion limit.