---
title: Recursion vs Iteration: Differences, Examples, When to Use
url: https://www.masaischool.com/resources/recursion-vs-iteration-difference
description: Recursion vs iteration: a difference table, three problems solved both ways with real output, Python's recursion limit, tail recursion and a decision guide.
updated: 2026-12-01
publisher: Masai (https://www.masaischool.com)
---

# Recursion vs iteration: the difference, with code and a decision guide

> **Short answer**
>
> Recursion solves a problem by having a function call itself on a smaller input, while iteration repeats a block with a loop. Both can solve the same problems. Recursion is shorter for trees and divide-and-conquer but uses call-stack memory and hits depth limits; iteration uses constant extra memory and is usually faster in Python.

Recursion and iteration are two ways to repeat work. Everything one can do, the other can do, so the real question is which is clearer and safer for the problem in front of you. This page gives a difference table, then runs the same problems both ways in Python 3.9 so the output is real, shows what happens when recursion goes too deep, explains why tail recursion does not help in Python, and ends with a decision guide.

If you are new to the idea, start with [what is recursion](https://www.masaischool.com/resources/what-is-recursion), which covers base cases and the call stack. For the cost vocabulary used below, see [time complexity and Big O](https://www.masaischool.com/resources/time-complexity-and-big-o-explained).

## The difference between recursion and iteration

Recursion repeats by calling the function again on a smaller input until a base case stops it; iteration repeats by running a loop until its condition fails. The practical differences are memory, speed, readability and risk of failure.

| Point | Recursion | Iteration |
|---|---|---|
| How it repeats | Function calls itself with a smaller input | for or while loop |
| Stops when | Base case is reached | Loop condition becomes false |
| State is held in | Arguments and local variables of each call | Variables updated in place |
| Extra memory | One stack frame per active call: O(depth) | Usually O(1) |
| Speed in Python | Slower: each call has overhead | Faster |
| Failure mode | RecursionError, or a stack overflow in other languages | Infinite loop if the condition never changes |
| Natural fit | Trees, graphs, divide and conquer, backtracking | Counting, scanning arrays, running totals |
| Code size | Often shorter for nested structures | Often shorter for flat sequences |

"Infinite recursion" and "infinite loop" are the same bug in different clothes: nothing moves the input towards the stopping condition.

## The same problems solved both ways

Factorial, digit sum and string reversal are the usual textbook trio. Each function below has a recursive and an iterative version, and the output proves they agree.def fact_rec(n): return 1 if n <= 1 else n * fact_rec(n - 1) def fact_iter(n): result = 1 for k in range(2, n + 1): result *= k return result def sum_digits_rec(n): return n if n < 10 else n % 10 + sum_digits_rec(n // 10) def sum_digits_iter(n): total = 0 while n: n, d = divmod(n, 10) total += d return total def reverse_rec(s): return s if len(s) <= 1 else reverse_rec(s[1:]) + s[0] def reverse_iter(s): out = [] for ch in s: out.insert(0, ch) return "".join(out) print(fact_rec(10), fact_iter(10)) print(sum_digits_rec(98765), sum_digits_iter(98765)) print(reverse_rec("recursion"), reverse_iter("recursion"))

Output: 3628800 3628800, then 35 35, then noisrucer noisrucer. Note that reverse_rec builds a new string at every level, so it is O(n^2) in time and the recursion is O(n) deep. A loop that appends to a list and joins once would be better still; the insert(0, ...) in the iterative version is also O(n^2), which is a reminder that iteration is not automatically faster.

Now a case where recursion earns its place: a tree. Each node lists its children, and we want a pre-order traversal (node first, then its children left to right).# Tree traversal: recursion is shorter, iteration needs an explicit stack tree = {"A": ["B", "C"], "B": ["D", "E"], "C": ["F"], "D": [], "E": [], "F": []} def preorder_rec(node): out = [node] for child in tree[node]: out += preorder_rec(child) return out def preorder_iter(root): out, stack = [], [root] while stack: node = stack.pop() out.append(node) stack.extend(reversed(tree[node])) # reversed so the left child pops first return out print(preorder_rec("A")) print(preorder_iter("A"))

Output: ['A', 'B', 'D', 'E', 'C', 'F'] from both. The recursive version reads like the definition. The iterative one needs an explicit stack, a reversed call so the left child pops first, and more care. You have not removed the stack by writing a loop; you have moved it from the call stack into a list you manage yourself. That is the standard way to convert any recursion to iteration, and it is also how you get around recursion limits.

## What goes wrong: Python's recursion limit and stack memory

Every active call occupies a stack frame holding its arguments, locals and return address. Python caps the depth with a limit; the default is 1000 and you can read it with sys.getrecursionlimit(). Go beyond it and Python raises RecursionError. This demo counts down from 5000 recursively, then with a loop from 1,000,000, then raises the limit.import sys def count_down(n): return 0 if n == 0 else count_down(n - 1) def count_down_loop(n): while n: n -= 1 return 0 print("limit:", sys.getrecursionlimit()) try: count_down(5000) except RecursionError as e: print("RecursionError:", e) print("loop with 1,000,000:", count_down_loop(1_000_000)) sys.setrecursionlimit(20000) # raising the limit is allowed, and risky print("recursive with 5000 after raising limit:", count_down(5000))

Output: limit: 1000, then RecursionError: maximum recursion depth exceeded in comparison, then loop with 1,000,000: 0, then recursive with 5000 after raising limit: 0. The loop handled a million steps with no trouble. Raising the limit works for modest depths, but the limit exists to protect the real C stack: set it very high and Python can crash the interpreter instead of raising a tidy error. The [sys documentation](https://docs.python.org/3/library/sys.html#sys.setrecursionlimit) says so itself, and the best fix for very deep recursion is a loop or an explicit stack.

Stack memory is the second cost. A recursion that goes n deep keeps n frames alive, so its space complexity is O(n) even when the function stores nothing else. Merge sort recursion is only O(log n) deep, which is why it is safe; a recursive sum over a list of 100,000 items is not. Other languages differ: Java throws StackOverflowError when the thread's stack is used up, while C and C++ programs typically crash with a stack overflow. The depth you can reach depends on the language, the frame size and the settings, so check yours rather than assuming.

Speed is the third. A rough measurement of summing 1 to 900 recursively and with a loop, from one run on a laptop:import time, sys sys.setrecursionlimit(5000) def sum_rec(n): return 0 if n == 0 else n + sum_rec(n - 1) def sum_loop(n): t = 0 for i in range(1, n + 1): t += i return t def bench(fn, n, reps): s = time.perf_counter() for _ in range(reps): fn(n) return (time.perf_counter() - s) / reps * 1e6 n = 900 a, b = bench(sum_rec, n, 2000), bench(sum_loop, n, 2000) print(sum_rec(n) == sum_loop(n)) print(f"recursive {a:.0f} us, loop {b:.0f} us, ratio about {a / b:.1f}x (n={n})")

Output from that run: True, then recursive 96 us, loop 24 us, ratio about 4.0x (n=900). Your numbers will differ; the recursive version being several times slower will not. Python has no tail-call optimisation, which is the next section.

## Tail recursion: the truth in Python

A tail-recursive function makes its recursive call as the very last action and carries the running result in an argument. Languages such as Scheme can reuse the same frame for such calls, so depth never grows. Python does not do this. The function below is written in tail form and still overflows.import sys def total_tail(n, acc=0): # written in "tail" form: the call is the last thing if n == 0: return acc return total_tail(n - 1, acc + n) print(total_tail(500)) try: total_tail(5000) except RecursionError: print("tail form still overflows at 5000: Python does not remove tail calls") def total_loop(n): # what a tail-call-optimising language would turn it into acc = 0 while n: acc, n = acc + n, n - 1 return acc print(total_loop(5000))

Output: 125250, then tail form still overflows at 5000: Python does not remove tail calls, then 12502500. Guido van Rossum, Python's creator, explained in a 2009 blog post why he does not want tail-recursion elimination: it breaks readable stack traces, code that relied on it would not run on other implementations, and he calls it unpythonic. So in Python, the tail form is just a recursion with an extra argument; if depth matters, write the loop shown in total_loop. Some languages, Scheme among them, do guarantee it. JavaScript's specification describes tail calls, but do not rely on them in practice.

## Which should you use? A decision guide

| Situation | Choose | Why |
|---|---|---|
| Tree or graph traversal, nesting of unknown depth | Recursion | The code mirrors the structure; depth is usually small (a balanced tree is about log n deep) |
| Divide and conquer such as merge sort and quicksort | Recursion | Depth is O(log n) for balanced splits |
| Generate all subsets, permutations or board placements | Recursion | See [backtracking explained](https://www.masaischool.com/resources/backtracking-explained) |
| Sum, count, search or scan over a flat list | Iteration | One pass; no frames needed |
| Depth could reach thousands or more (linked list of 100,000 nodes, long chain) | Iteration or explicit stack | Python raises RecursionError near 1000 frames |
| Overlapping sub-problems (Fibonacci, grid paths) | Recursion with memo, or an iterative table | Plain recursion is exponential; see [types of dynamic programming](https://www.masaischool.com/resources/types-of-dynamic-programming) |
| Performance-critical inner loop | Iteration | No call overhead |

In interviews, write the recursion first if it is clearer, state its time and space cost out loud (including the O(depth) stack), and offer the iterative version if the interviewer asks about large inputs. For more practice problems, see [DSA interview questions](https://www.masaischool.com/resources/dsa-interview-questions) and the [data structures and algorithms path](https://www.masaischool.com/resources/data-structures-and-algorithms).

## Frequently asked questions

### What is the main difference between recursion and iteration?

Recursion repeats by a function calling itself on a smaller input until a base case, while iteration repeats with a loop until a condition fails. Recursion keeps one stack frame per active call, so it uses O(depth) memory; a loop usually needs O(1). Both can express the same algorithms.

### Is recursion better than iteration?

Neither is better in general. Recursion is clearer for trees, graphs, divide and conquer and backtracking. Iteration is faster and safer for flat loops and very deep repetition, especially in Python, which has no tail-call optimisation and a default depth limit of 1000. Pick the one that matches the structure of the data.

### When should I use recursion?

Use it when the problem is defined in terms of smaller copies of itself and the depth stays small: tree traversal, merge sort, generating subsets or permutations, and exploring graphs or mazes. Avoid it for plain counting or scanning, or when the depth could reach thousands of calls.

### Is recursion slower than iteration?

In Python, yes. Every call creates a frame, and a quick test summing 1 to 900 ran roughly four times slower recursively on one laptop. In compiled languages the gap is smaller, and a compiler may remove some calls. Naive recursion can also repeat work, as in Fibonacci, which is a separate problem fixed by memoization.

### Why does Python raise RecursionError?

Python limits call depth, 1000 by default, to stop runaway recursion from crashing the interpreter. You can read it with sys.getrecursionlimit() and change it with sys.setrecursionlimit(), but a very high value risks a real crash. For deep structures, rewrite with a loop or an explicit stack.

### Does Python support tail recursion optimisation?

No. A function written in tail form still uses one frame per call and raises RecursionError at the limit, as the 5000-deep test above shows. If you need constant stack use, write the loop yourself.

### Can every recursive function be written as a loop?

Yes. Any recursion can be converted by managing your own stack, as in the iterative tree traversal above. Simple linear recursions turn into plain loops with a couple of variables, while branching recursions need the explicit stack, so the converted version is often longer.
