Lambda Functions

Difficulty: Intermediate

Lambda functions are small anonymous functions defined with the `lambda` keyword. Unlike regular functions defined with `def`, a lambda is a single expression that is evaluated and returned automatically -- no `return` statement is needed or allowed. The syntax is `lambda parameters: expression`. Lambdas are most useful as short throwaway functions passed as arguments to higher-order functions like `map()`, `filter()`, and `sorted()`.

The `map()` function applies a given function to every item in an iterable and returns a map object (a lazy iterator). It is commonly used with lambda functions to transform data in a concise, functional style. For example, `map(lambda x: x 2, numbers)` squares every element. Since `map()` returns an iterator, you typically wrap it in `list()` to see all results at once.

The `filter()` function works similarly but keeps only the items for which the function returns `True`. It is the functional equivalent of a list comprehension with an `if` clause. Combined with lambda, it reads naturally: `filter(lambda x: x > 0, numbers)` keeps only positive numbers. Like `map()`, it returns a lazy iterator.

The `reduce()` function, found in the `functools` module, applies a two-argument function cumulatively to the items of an iterable, reducing them to a single value. For example, `reduce(lambda a, b: a + b, [1, 2, 3, 4])` computes `((1 + 2) + 3) + 4 = 10`. While powerful, `reduce()` can be harder to read than an explicit loop, so Python's style guide recommends using it judiciously.

The `sorted()` function and the `list.sort()` method both accept a `key` parameter -- a function that extracts a comparison key from each element. Lambda functions are the most common way to supply custom sort keys. For instance, `sorted(words, key=lambda w: len(w))` sorts strings by length. You can also sort tuples, dictionaries, and objects by any attribute or computed value using this pattern.

Code examples

Lambda Basics

# A simple lambda that adds two numbers
add = lambda a, b: a + b
print(add(3, 5))

# Lambda with a conditional expression
classify = lambda x: "even" if x % 2 == 0 else "odd"
print(classify(4))
print(classify(7))

A lambda is a one-line anonymous function. The first lambda takes two parameters and returns their sum. The second uses a conditional expression (ternary) to classify a number as even or odd.

map() and filter() with Lambda

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

squared = list(map(lambda x: x  2, numbers))
print(f"Squared: {squared}")

evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Evens: {evens}")

# Chaining: square only the even numbers
result = list(map(lambda x: x  2, filter(lambda x: x % 2 == 0, numbers)))
print(f"Squared evens: {result}")

map() transforms each element, filter() keeps elements that satisfy the condition. Nesting them together chains the operations: first filter for evens, then square the results.

reduce() for Accumulation

from functools import reduce

numbers = [1, 2, 3, 4, 5]

total = reduce(lambda a, b: a + b, numbers)
print(f"Sum: {total}")

product = reduce(lambda a, b: a * b, numbers)
print(f"Product: {product}")

largest = reduce(lambda a, b: a if a > b else b, numbers)
print(f"Max: {largest}")

reduce() takes a two-argument function and applies it cumulatively. For the sum: ((((1+2)+3)+4)+5) = 15. For the product: ((((1*2)*3)*4)*5) = 120. The max example compares pairs and keeps the larger value.

sorted() with key Lambda

students = [
    {"name": "Charlie", "grade": 82},
    {"name": "Alice", "grade": 95},
    {"name": "Bob", "grade": 88},
]

by_grade = sorted(students, key=lambda s: s["grade"])
for s in by_grade:
    print(f"{s['name']}: {s['grade']}")

print("---")

words = ["banana", "pie", "Washington", "cat"]
by_length = sorted(words, key=lambda w: len(w))
print(by_length)

The key parameter extracts the value used for comparison. Sorting students by grade produces ascending order. Sorting words by length groups shorter words first. Use reverse=True for descending order.

Key points

Concepts covered

Lambda Syntax, map(), filter(), reduce(), sorted() with key