Python Tutorial 0/52 lessons ~6 min read Lesson 14
Recursion
Recursion — a function that calls itself — is natural for tree/graph traversal, divide-and-conquer, and parsing.
Course progress0%
Focus
9 guided sections
Practice signal
Examples included
Career prep
Foundation builder
Introduction
Recursion — a function that calls itself — is natural for tree/graph traversal, divide-and-conquer, and parsing. Python's default recursion limit is 1000 frames.
Understanding the topic
Core concepts to understand:
- Always have a base case.
- Each recursive call must move toward the base.
sys.setrecursionlimitcan raise the cap.- Use
@functools.lru_cachefor memoization.
Syntax reference
Visual flow / code:
python
from functools import lru_cache@lru_cache(maxsize=None)def fib(n: int) -> int:if n < 2:return nreturn fib(n - 1) + fib(n - 2)print(fib(50)) # instant with memoization
Execution workflow
1Recursion Workflow
1 / 4Step 1
Always have a base case.
Apply this step while implementing recursion in real code.
Real-world use
Memoized recursion turns exponential algorithms (naive fib) into linear ones — a one-line decorator. Standard tool in dynamic programming.
Best practices
- Always define the base case first.
- Add
@lru_cachefor overlapping subproblems. - Prefer iteration when depth is huge.
Common mistakes
- Missing base case → RecursionError.
- Python has no tail-call optimization.
Hands-on exercise
Interview preparation — practice these questions:
- What's tail recursion?
- Why does Python lack TCO?
- What is memoization?
Summary
In summary: Base case + smaller problem. lru_cache supercharges recursion.
Ready to mark this lesson complete?Track your journey across the entire course.