Episode 24 of 29

Lambdas

Learn how to create small anonymous functions using lambda expressions.

Lambda functions are small, anonymous functions defined in a single line.

Basic Syntax

# Regular function
def add(a, b):
    return a + b

# Lambda equivalent
add = lambda a, b: a + b
print(add(3, 5))  # 8

Common Uses

# Sorting with custom key
people = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
people.sort(key=lambda p: p[1])
print(people)  # Sorted by age

When to Use Lambdas

  • Short, simple functions used only once
  • As arguments to map(), filter(), sorted()
  • When a full def would be overkill