6.3 map, filter, and reduce
map(), filter(), and reduce() help split data processing into clear steps. They are often used with short lambda functions. A lambda is an anonymous function, useful for a very small transformation or test.
Data Processing Pipeline
Think of a list as data moving through a pipeline:
filter()decides which elements stay.map()transforms each element.reduce()combines many values into one result.
Loading interactive lab...
Sum of Odd Squares
The program below computes the sum of the squares of all odd numbers from 0 through 9.
python
from functools import reduce
numbers = list(range(10))
print("numbers =", numbers)
odds = list(filter(lambda x: x % 2 == 1, numbers))
print("odds =", odds)
squares = list(map(lambda x: x ** 2, odds))
print("squares =", squares)
total = reduce(lambda x, y: x + y, squares)
print("total =", total)Output:
text
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
odds = [1, 3, 5, 7, 9]
squares = [1, 9, 25, 49, 81]
total = 165Loading concept check...
When to Use lambda
lambda is useful for very short anonymous functions. For example, lambda x: x ** 2 means “take x and return its square.”
If the logic is long, use a normal def function. Do not sacrifice readability just to be shorter.
Loading concept check...
Loading practice...