map(), filter(), and reduce() help split data processing into clear steps. They are often used with short lambda functions.
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.
Pipeline checkpoints: filter → map → reduce
Advance one checkpoint at a time and watch values get rejected, transformed, or folded into the accumulator.
[1, 2, 3, 4, 5, 6]
Waiting…
Waiting…
Waiting…
Only source data is visible; advance to run filterSum of Odd Squares
The program below computes the sum of the squares of all odd numbers from 0 through 9.
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)numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
odds = [1, 3, 5, 7, 9]
squares = [1, 9, 25, 49, 81]
total = 165KNOWLEDGE QUIZ
Understanding lambda
A lambda creates a short function without a declared name. Its syntax is lambda parameters: expression. Parameters go to the left of the colon; exactly one expression goes to the right. That expression is returned implicitly, so there is no return keyword. For example, lambda x: x ** 2 behaves like a regular function whose body is only return x ** 2.
def square(x):
return x ** 2
square_lambda = lambda x: x ** 2
print(square(5))
print(square_lambda(5))A lambda is a function object: you may assign it to a variable or pass it directly to tools such as map, filter, and sorted that expect a function argument. It may also accept multiple parameters, as in lambda x, y: x + y.
Use lambda for a one-rule function that is readable at a glance, such as key=lambda item: item[1]. If the logic needs multiple steps, loops, exception handling, or a descriptive name, use a regular def. Brevity is not the goal; readability is.
Lambda machine: parameters in, expression out
A regular function and a lambda follow the same core rule. Choose an expression, then send a value through it.
lambda x: x ** 2KNOWLEDGE QUIZ
KNOWLEDGE QUIZ
Rebuild the odd-square pipeline
Use filter, map, and reduce to sum the squares of odd numbers from 1 through 20. Print each stage.
Sort scores with a lambda key
Given students = [("Lin", 88), ("Mia", 95), ("Bo", 76)], use sorted() and a lambda to sort by score descending.
Clean temperature data
Given values = [-5, 12, None, 31, 18, 45, 8], filter out None and values outside 0–40, map Celsius to Fahrenheit, then use reduce to sum the results. Print each stage.