LearnPy Hub
FunctionsIntermediateLesson 14 of 32

Recursion & Lambda

Watch the ideaA function that calls itself
def fact(n):
    if n == 1:
        return 1
    return n * fact(n - 1)

print(fact(3))
Call stack
fact(3)3 * fact(2)

fact(3) needs fact(2) first, so it waits.

1Level 1 · BasicsBasics

This lesson covers two ideas about functions. Recursion is a function that calls itself to solve smaller versions of a problem. Lambda functions are tiny one-line functions without a name, handy for sorting and filtering.

Recursion: solving a problem with a smaller copy of itself

Think of Russian nesting dolls: to find the smallest doll, open the doll, then do the same thing with the doll inside, until there's nothing left to open. Factorial works the same way: 5! = 5 × 4!, and 4! = 4 × 3!, and so on, down to 1! = 1.

def factorial(n):
    if n <= 1:          # base case: stop here
        return 1
    return n * factorial(n - 1)   # recursive case

Every recursive function needs two parts:

  1. A base case that answers directly without recursing. Without it the function calls itself forever and Python stops it with a RecursionError.
  2. A recursive case that moves closer to the base case, for example n - 1.

Recursion shines for naturally nested problems: folders inside folders, family trees, and splitting a problem in half (like binary search). For simple counting, a loop is usually faster and clearer.

Lambda: a function in one line

square = lambda x: x * x
square(5)   # 25

A lambda takes parameters before the colon and returns the expression after it. It's the same as def square(x): return x * x. You'll mostly use lambdas as arguments to other functions:

sorted(students, key=lambda s: s["cgpa"])   # sort by cgpa
max(words, key=len)                          # longest word
list(filter(lambda n: n > 0, nums))          # keep positives
list(map(lambda n: n * 2, nums))             # double each

The key function tells sorted, max and min what to compare. Add reverse=True to sort from high to low.

Key points: a recursive function calls itself and must have a base case; each call should move towards the base case; lambda x: expr is a small anonymous function; pass it as key= to sort or find max/min by any rule.

See it in actionRecursion stacks up, then unwinds

Each call to fact() adds a frame on top. Watch them return one by one.

Step-by-step

Try it yourselfExample 1: Factorial with recursion

Each call waits for the smaller call to finish. Try factorial(10).

example_1.py
Output appears here
Fill in the blanks

Factorial

Fill the blanks so the recursive function prints 120 (5! = 5 × 4 × 3 × 2 × 1).

blanks.py
def fact(n):
    if n == :
        return 1
    return n * fact(n  1)

print(fact(5))

Example 2: Watching recursion happen

The indentation shows each call going deeper, then returning.

example_2.py
Output appears here

Example 3: Sum of digits, recursively

The last digit plus the digit sum of the rest. The base case is a single digit.

example_3.py
Output appears here
Fix the bug

Never-ending recursion

This should count down 3 2 1 on separate lines, but it never stops. Add the missing base case.

buggy.py
Your turn

Power, recursively

Write a recursive function power(b, e) that returns b to the power e without using ** or pow. Print power(2, 10), which is 1024.

my_code.py

Example 4: Sorting with lambda

The key function picks what to compare.

example_4.py
Output appears here
Fill in the blanks

Sort by length

Fill the blanks so the words are sorted from shortest to longest: ['ox', 'cat', 'horse'].

blanks.py
words = ["horse", "ox", "cat"]
print(sorted(words, key= w: (w)))

Example 5: map and filter

map() applies a function to every item; filter() keeps items where it returns True.

example_5.py
Output appears here
Your turn

Double with map

Use map with a lambda to double every number in [3, 5, 8] and print [6, 10, 16].

my_code.py

2Level 2 · IntermediateRecursion on lists and strings, lambdas as keys

Every recursion needs two parts

A base case that answers directly, and a recursive case that makes the problem smaller. Forget the base case and Python stops you with RecursionError after about 1000 calls.

Recursing on sequences

"The sum of a list is its first item plus the sum of the rest." Many list and string problems can be phrased this way: reverse, count, check palindromes, flatten nested lists.

Lambdas with sorted, max and min

max(students, key=lambda s: s["gpa"]) finds the best student. Sorting by several things: key=lambda s: (-s["gpa"], s["name"]).

See it in actionFlattening nested lists recursively

Watch the call stack grow for each inner list, then shrink as results come back.

Step-by-step

Example 6: Recursion on strings

Each function shrinks the string by one character until it's empty.

example_6.py
Output appears here

Example 7: Lambdas as sort keys

Highest GPA first; ties go alphabetically by name.

example_7.py
Output appears here

3Level 3 · AdvancedMemoization, backtracking and functional tools

Memoization

Naive fib(35) makes about 30 million calls because it solves the same small problems again and again. Remembering each answer in a dictionary (a memo) cuts that to under 100. (In the Decorators lesson, @functools.lru_cache does the remembering for you.) This idea is the heart of dynamic programming.

Backtracking

To list all arrangements or subsets, choose an option, recurse, then undo the choice and try the next. Puzzles like N-Queens and Sudoku use this.

Recursion depth

Python's default limit is about 1000 nested calls. For deep problems, convert to a loop with your own stack.

Functions that make functions

A function can return a lambda that remembers the outer function's arguments: make_tax(0.15) gives back a ready-made VAT function. Pair it with map() and filter(). (The functools module, in the next lesson, adds reduce and partial.)

See it in actionBacktracking builds every subset

Watch chosen grow and shrink as the function tries "take it" and then "leave it".

Step-by-step

Example 8: Memoization makes recursion fast

The counter shows how many calls each version makes.

example_8.py
Output appears here

Example 9: map, filter and a function that makes functions

make_tax() returns a new function that remembers its rate. Try making a 5% tax too.

example_9.py
Output appears here
Common mistakeA recursive function without a base case, or one that never reaches it (for example calling f(n + 1) when the base case is n == 0), ends with RecursionError: maximum recursion depth exceeded.
Exercise · predict the output

What does this print?

def f(n):
    if n == 0:
        return 0
    return n + f(n - 1)
print(f(4))
Quick quiz · 5 questions
1. What is the base case in a recursive function?
2. What does (lambda x: x + 1)(4) evaluate to?
3. How do you sort a list of words by length?
4. What error do you get when recursion never stops?
5. What does list(filter(lambda n: n % 2 == 0, [1, 2, 3, 4])) give?
Ready to practice recursion & lambda?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Recursion & Lambda · LearnPy Hub