Reading history

Python Recursion: Base Case, Call Stack and Memoization

4 min read 2 views

Learn recursion in Python: base and recursive cases, the call stack, recursive list processing, lru_cache memoization, and the recursion limit.

Recursion is when a function solves a problem by calling itself on a smaller version of the same problem. It is a natural fit for data that contains smaller copies of itself, such as folders inside folders, nested lists and trees, and for divide-and-conquer algorithms. This lesson shows how to write a recursive function safely, how to speed one up with caching, and when a loop is the better choice.

In this lesson you will learn

  • The two parts of every recursive function: base case and recursive case
  • How Python tracks recursive calls on the call stack
  • Recursion on lists and nested structures
  • Memoization with functools.lru_cache
  • The recursion limit and RecursionError

Base Case and Recursive Case

def factorial(n):
    if n <= 1:              # base case: stops the recursion
        return 1
    return n * factorial(n - 1)   # recursive case: a smaller problem

print(factorial(5))

def countdown(n):
    if n == 0:
        print("Lift off!")
        return
    print(n)
    countdown(n - 1)

countdown(3)

def total(items):
    if not items:
        return 0
    return items[0] + total(items[1:])

print(total([4, 8, 15, 16, 23, 42]))

def flatten(nested):
    result = []
    for x in nested:
        if isinstance(x, list):
            result.extend(flatten(x))   # recurse into sub-lists
        else:
            result.append(x)
    return result

print(flatten([1, [2, [3, 4], 5], [[6]], 7]))

Output

120
3
2
1
Lift off!
108
[1, 2, 3, 4, 5, 6, 7]
  • Every recursive function needs a base case that returns without calling itself. For factorial it is n <= 1. Without it, the calls never stop.
  • The recursive case calls the function on a smaller input, n - 1, so each call moves closer to the base case.
  • Python keeps each unfinished call on the call stack. factorial(5) waits for factorial(4), which waits for factorial(3), and so on; the answers are multiplied together as the calls return: 1 → 2 → 6 → 24 → 120.
  • total sums a list as “first item plus the total of the rest”, with the empty list as base case.
  • flatten shows where recursion shines: the nesting depth is unknown, so a fixed number of loops cannot handle it, but a function that calls itself on each sub-list can.

Memoization and the Recursion Limit

import sys
from functools import lru_cache

calls = 0
def fib_slow(n):
    global calls
    calls += 1
    return n if n < 2 else fib_slow(n - 1) + fib_slow(n - 2)

print(fib_slow(25), "calls:", calls)

@lru_cache(maxsize=None)            # remember results already computed
def fib_fast(n):
    return n if n < 2 else fib_fast(n - 1) + fib_fast(n - 2)

print(fib_fast(25), fib_fast(90))
print("cache:", fib_fast.cache_info().hits, "hits")

print("recursion limit:", sys.getrecursionlimit())
def forever(n):
    return forever(n + 1)
try:
    forever(0)
except RecursionError as e:
    print("RecursionError:", e)

Output

75025 calls: 242785
75025 2880067194370816120
cache: 89 hits
recursion limit: 1000
RecursionError: maximum recursion depth exceeded
  • The plain Fibonacci function calls itself twice per step, recomputing the same values again and again: 242,785 calls for fib_slow(25). Its running time grows exponentially.
  • @lru_cache remembers each result. Every Fibonacci number is computed once, so fib_fast(90) is instant. This technique is called memoization and is the starting point of dynamic programming.
  • Python limits the depth of the call stack, 1000 by default, to protect against crashes. Exceeding it raises RecursionError. A missing or unreachable base case is the usual cause.
  • Python does not optimise tail calls, so very deep recursion (for example over a list of 100,000 items) should be rewritten as a loop.

Recursion vs Iteration

RecursionLoop
Best forTrees, nested data, divide and conquerSimple repetition over a sequence
MemoryOne stack frame per callConstant
Depth limitAbout 1000 calls by defaultNone
ReadabilityVery clear for self-similar problemsClearer for linear tasks

Recursive algorithms appear throughout the Data Structures and Algorithms tutorials, for example in tree traversal and merge sort.

Common Mistakes

  1. No base case, or one that is never reached (for example, subtracting 2 from an odd number until it equals 0).
  2. Not returning the recursive result: writing factorial(n - 1) instead of return n * factorial(n - 1).
  3. Exponential recursion without caching, as in plain Fibonacci.
  4. Using recursion for long flat sequences, which hits the depth limit.

Practice Exercises

Exercise 1. Write a recursive function that reverses a string.

Show answer
def reverse(s):
    if len(s) <= 1:
        return s
    return reverse(s[1:]) + s[0]

print(reverse("python"))   # nohtyp

Exercise 2. Write power(base, exp) recursively for a non-negative integer exponent.

Show answer
def power(base, exp):
    if exp == 0:
        return 1
    return base * power(base, exp - 1)

print(power(2, 10))   # 1024

Frequently Asked Questions

Can I raise the recursion limit?

Yes, with sys.setrecursionlimit(), but setting it too high can crash the interpreter when the real C stack runs out. Rewriting the function as a loop is usually the better fix.

Is recursion slower than a loop in Python?

Usually a little, because each function call has overhead. The difference matters only for very large inputs; choose whichever version is clearer.

Summary

  • A recursive function calls itself on a smaller problem until it reaches a base case.
  • Each call waits on the call stack until the calls below it return.
  • @lru_cache removes repeated work from recursive functions.
  • Python limits recursion depth; use loops for long linear tasks.

Next: Python JSON.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *