The short answer
A recursive function is a function that calls itself. To avoid running forever, it has two parts: a base case that returns an answer without making another call, and a recursive case that calls itself with a smaller or simpler input. Each call adds a layer of work, and the answers come back up the chain as the calls finish.
The two parts every recursive function needs
- Base case: the simplest input, which the function answers directly. For a list, the base case is often an empty list.
- Recursive case: the function calls itself with an input that is closer to the base case.
If the base case is missing, or the recursive case never gets closer to it, the function keeps calling itself and never finishes.
A worked example: summing a list
The following function adds up the numbers in a list by taking the first number and adding the sum of the rest.
def sum_list(numbers):
if not numbers: # base case: empty list sums to 0
return 0
return numbers[0] + sum_list(numbers[1:]) # recursive case
print(sum_list([3, 7, 2])) # 12
Here is the chain of calls for [3, 7, 2]:
- sum_list([3, 7, 2]) returns 3 plus sum_list([7, 2]).
- sum_list([7, 2]) returns 7 plus sum_list([2]).
- sum_list([2]) returns 2 plus sum_list([]).
- sum_list([]) hits the base case and returns 0.
The answers then come back up: 2 + 0 is 2, 7 + 2 is 9, and 3 + 9 is 12. The slicing step, numbers[1:], creates a new list on every call, so this version does more copying than necessary. It is clear, though, and it shows the pattern.
What happens in memory: the call stack
Each call gets its own stack frame, a small block of memory that holds its arguments, its local variables and the place to return to. While calls are waiting for answers, their frames stack up. As the base case returns, the frames are removed one at a time. This last-in, first-out pattern is the same one described in stack operations in data structure.
What a stack overflow looks like
A function with no base case never stops. This one prints a number and then calls itself again with a smaller number, but it never checks for a stopping point:
def count_down(n):
print(n)
return count_down(n - 1) # no base case, so this never stops
In Python, the program eventually fails with a RecursionError saying the maximum recursion depth has been exceeded. Python’s default limit is 1,000 nested calls. You can change it with sys.setrecursionlimit, but raising the limit does not fix a missing base case. Other languages report the same problem differently: Java throws a StackOverflowError, and C programs often crash.
Recursion versus loops
Any recursive function can be rewritten as a loop, and most loops can be written as recursion. Loops usually use less memory and do not hit a depth limit. Recursion often reads more clearly when the data itself is nested, such as trees, folders or nested lists. The same sum written as a loop looks like this:
def sum_list_loop(numbers):
total = 0
for number in numbers:
total += number
return total
Tail recursion and Python
A tail call is a recursive call that is the very last thing a function does. Some languages can reuse the current stack frame for tail calls, which avoids growing the stack. Python does not do this, so a long chain of tail calls still uses stack depth.
Common mistakes
- Forgetting the base case. The calls never stop.
- Moving away from the base case. Calling with n + 1 instead of n - 1 never reaches it.
- Repeating work. A naive recursive Fibonacci function solves the same smaller problems many times over.
- Using recursion on very large inputs. A list with a million items can exceed the stack limit, so a loop is safer there.
When recursion fits
Recursion fits problems that break naturally into smaller copies of themselves, such as tree traversal, nested data and divide-and-conquer sorting. For more worked examples, see recursive algorithm examples. For a simple total over a flat list, a loop is usually the clearer choice.