Learn Python
>>> functions.recursion

Recursion in Python

#concept

Recursion is when a function calls itself to solve a smaller version of the same problem, continuing until it reaches a base case simple enough to answer directly without another call. Every recursive function needs exactly that: a base case that stops the recursion, and a recursive case that makes progress toward it.

#how it works
1

Identify the base case

The simplest version of the problem, answerable directly with no further recursion.

2

Identify the recursive case

How to reduce the problem toward the base case, usually by calling the function again with a smaller input.

3

Each call waits for the next

Building up a chain of paused calls, each waiting on the one it made.

4

The chain unwinds from the base case

Once the base case is hit, calls start returning back up, each completing its paused work.

5

A broken base case recurses forever

Without genuine progress toward the base case, Python eventually raises a RecursionError.

#example
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
 
print(factorial(5))
Output
120
1factorial(5) is not the base case, so it calls factorial(4) and waits, planning to multiply the result by 5.
2factorial(4) does the same, calling factorial(3), and so on down to factorial(1).
3factorial(1) hits the base case (n <= 1) and returns 1 directly, with no further recursive call.
4That 1 flows back up: factorial(2) returns 2 * 1 = 2, factorial(3) returns 3 * 2 = 6, factorial(4) returns 4 * 6 = 24, and finally factorial(5) returns 5 * 24 = 120.
#complexity
time O(n) for this factorial example
space O(n)

Each recursive call waits on the stack until a deeper call returns, so a recursive function that makes n nested calls uses O(n) space for that call stack — unlike an equivalent loop, which typically uses O(1) space. This is one reason very deep recursion can hit Python's recursion limit or use noticeably more memory than a loop.

#use cases
Naturally recursive problems, like traversing a tree or a nested folder structure of unknown depth
Mathematical definitions that are already recursive, like factorials or the Fibonacci sequence
Divide-and-conquer algorithms, such as quicksort and merge sort, which repeatedly split a problem in half
Situations where an iterative loop would need to manually track state that recursion handles automatically through its call stack

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.