⚡IntermediateFunctional Python

Lambda, map, filter, reduce

Anonymous functions and higher-order functions for concise data transformation.

Overview

Functional programming treats functions as first-class values they can be passed to other functions, returned from functions, and stored in variables. Python supports this style with lambda expressions and higher-order functions like map(), filter(), and reduce(). **lambda** creates an anonymous (nameless) one-expression function: `lambda x: x * 2`. They're ideal as short callbacks where defining a full `def` would be verbose. **map(func, iterable)** applies func to every element and returns a lazy iterator of results equivalent to a list comprehension `[func(x) for x in iterable]`. **filter(func, iterable)** returns elements for which func returns True equivalent to `[x for x in iterable if func(x)]`. **functools.reduce(func, iterable)** repeatedly applies func to accumulate a single result e.g. summing or multiplying all elements. In modern Python, list comprehensions are usually preferred over map/filter for readability. However, lambda + sorted/max/min with a key= argument is extremely common and idiomatic.

Key Points

  • •`lambda params: expression` one-liner anonymous function, single expression only
  • •`map(fn, iterable)` → lazy iterator; wrap in list() to materialise
  • •`filter(fn, iterable)` → keeps elements where fn(x) is truthy
  • •`functools.reduce(fn, iterable, initial)` → folds sequence to single value
  • •Key use case: `sorted(items, key=lambda x: x.age)` sort by attribute
  • •List comprehensions often read more clearly than map/filter for simple cases
  • •`operator` module has ready-made functions: operator.add, operator.itemgetter, etc.

Examples

lambda expressions

# Assigning to a variable
double = lambda x: x * 2
print(double(5))       # 10

# Multi-argument lambda
add = lambda a, b: a + b
print(add(3, 4))       # 7

# Commonly used as key= argument
points = [(1, 5), (3, 2), (2, 8), (4, 1)]
sorted_by_y = sorted(points, key=lambda p: p[1])
print(sorted_by_y)   # [(4,1),(3,2),(1,5),(2,8)]

words = ["banana", "apple", "cherry", "date"]
print(sorted(words, key=lambda w: len(w)))  # sort by length

map() and filter()

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

# map: apply a function to every element
squares = list(map(lambda x: x ** 2, numbers))
print(squares)   # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# filter: keep elements that satisfy a condition
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)     # [2, 4, 6, 8, 10]

# Chaining: square the even numbers
result = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, numbers)))
print(result)    # [4, 16, 36, 64, 100]

# Equivalent, more readable list comprehension:
result2 = [x**2 for x in numbers if x % 2 == 0]

reduce() and practical lambda patterns

from functools import reduce

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

# Sum using reduce
total = reduce(lambda acc, x: acc + x, nums)
print(total)    # 15

# Product using reduce
product = reduce(lambda acc, x: acc * x, nums)
print(product)  # 120

# Sort objects by multiple criteria
people = [
    {"name": "Alice", "age": 30},
    {"name": "Bob",   "age": 25},
    {"name": "Carol", "age": 30},
]
# Sort by age, then name
sorted_people = sorted(people, key=lambda p: (p["age"], p["name"]))
for p in sorted_people:
    print(p["name"], p["age"])

Common Mistakes

  • Using lambda where a named function would be clearer lambda is for simple, throwaway functions
  • Trying to use statements (if/else blocks, assignments) inside lambda only a single expression is allowed
  • Forgetting that map() and filter() return iterators, not lists wrap with list() if you need indexing

Note

Use lambda mainly as a key= argument to sorted(), min(), max(), or groupby(). For anything more complex than a simple expression, define a proper def function it's more readable and easier to test.

Exercises

Write Python code to solve each exercise. Run it in your browser and check your output.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

What does `lambda x, y: x if x > y else y` do?