Sub topic 2
Transforming and Selecting with `map` and `filter`
Assume you know def, list comprehensions, default arguments, and *args and **kwargs. This chapter focuses on how functions can be passed as values.
Transforming and selecting with `map` and `filter`
map applies a function to every item. filter keeps only items for which a function returns a truthy value. Both return iterators, so use list when you need all results immediately.
nums = [1, 2, 3, 4, 5, 6]
squares = list(map(lambda n: n * n, nums))
evens = list(filter(lambda n: n % 2 == 0, nums))
print(squares) # [1, 4, 9, 16, 25, 36]
print(evens) # [2, 4, 6]A lambda is a small anonymous function. It contains one expression and returns that expression's value.
flowchart TD
A[Input numbers] --> B[filter: keep even numbers]
B --> C[map: square each number]
C --> D[Output]Comprehensions or `map` and `filter`?
A list comprehension often expresses the same operation more clearly:
nums = [1, 2, 3, 4, 5, 6]
via_hof = list(map(lambda n: n * n, filter(lambda n: n % 2 == 0, nums)))
via_comp = [n * n for n in nums if n % 2 == 0]
print(via_hof) # [4, 16, 36]
print(via_comp) # [4, 16, 36]Use map or filter when you already have a named function or are composing an iterator pipeline. Prefer a comprehension when it makes the transformation and condition easier to read.
Combining values with `functools.reduce`
reduce repeatedly combines items into one value. The accumulator stores the result so far.
from functools import reduce
total = reduce(lambda acc, n: acc + n, [1, 2, 3, 4], 0)
print(total) # 10The initial value 0 also makes the empty-list case well defined. For simple sums, prefer the built-in sum; use reduce for a clear custom fold.
Closures: functions that remember their surroundings
A closure is a function that retains access to variables from the scope where it was created.
def make_multiplier(factor):
return lambda value: value * factor
double = make_multiplier(2)
print(double(5)) # 10The returned lambda remembers factor, even after make_multiplier has finished.
Exercise
What does list(filter(lambda n: n > 3, [1, 4, 2, 5])) return?
Show answer
[4, 5].