Skip to main content

Lambdas & Recursion

Beyond defining standard multi-line functions with def, Python allows quick one-line shortcut functions called lambdas, as well as functions that call themselves to solve repeating problems.

What is a Lambda Function?

A Lambda Function (lambda) is a small, anonymous function written on a single line without using def or return:

# Standard function
def double(number):
return number * 2

# Exact same function written as a one-line lambda
double_lambda = lambda number: number * 2

print(double_lambda(10)) # Output: 20

Where are Lambdas Actually Used?

Lambdas are most frequently used as quick sorting shortcuts when sorting complex lists like lists of tuples:

students = [("Alice", 88), ("Bob", 95), ("Charlie", 72)]

# Sort students by their score (the second item at index 1)
students.sort(key=lambda item: item[1])
print(students) # Output: [('Charlie', 72), ('Alice', 88), ('Bob', 95)]

What is Recursion?

Recursion happens when a function calls itself inside its own body. To stop the function from repeating forever and crashing your computer, every recursive function must have two rules:

  1. Base Case: The stopping condition where the function stops calling itself.
  2. Recursive Step: The step where the function calls itself with a smaller problem.
def countdown(number):
# 1. Base Case (Stop condition)
if number <= 0:
print("Blast off!")
return

# Print number and repeat with smaller number
print(number)
countdown(number - 1)

countdown(3)
# Output:
# 3
# 2
# 1
# Blast off!
Common Beginner Mistakes
  • Missing Base Case in Recursion: Forgetting a termination check causes a function to call itself indefinitely until it crashes with RecursionError: maximum recursion depth exceeded.

Quick Summary

  • Lambda Functions (lambda args: expression): Anonymous, concise one-line functions ideal for sorting keys, map(), or filter().
  • Recursion Mechanism: A function that calls itself with a reduced subset of the original problem.
  • Base Case Necessity: Every recursive function must contain a base condition that stops recursion and begins unwinding call frames.

What's Next?

Let's dive into Module 12.5: Comprehensions & Pythonic Patterns to learn powerful, elegant idioms for creating lists, sets, and dictionaries cleanly!