map() applies a function to every item. filter() keeps only the items where a function returns True. reduce() combines all the items into one value.
The program
python
from functools import reduce numbers = [1, 2, 3, 4, 5, 6] squares = list(map(lambda x: x ** 2, numbers)) evens = list(filter(lambda x: x % 2 == 0, numbers)) product = reduce(lambda a, b: a * b, numbers) print(squares) print(evens) print(product)
output
[1, 4, 9, 16, 25, 36] [2, 4, 6] 720
How it works
map()andfilter()return lazy objects, not lists. They produce items only when asked, solist()is needed to see them all at once.reduce()takes the first two items, combines them, then combines that result with the next item, and so on:((((1*2)*3)*4)*5)*6.reduce()is in thefunctoolsmodule.map()andfilter()are built-ins.- You can pass a normal function instead of a lambda:
list(map(str, numbers))turns every number into a string.
Another way: comprehensions and built-ins
Most Python code uses a list comprehension instead of map() and filter(), and a built-in such as sum() or math.prod() instead of reduce(). The results are the same:
python
import math numbers = [1, 2, 3, 4, 5, 6] print([x ** 2 for x in numbers]) print([x for x in numbers if x % 2 == 0]) print(math.prod(numbers))
output
[1, 4, 9, 16, 25, 36] [2, 4, 6] 720
An empty list
reduce() on an empty list raises a TypeError, because there is no first item to start with. Pass a starting value as the third argument to avoid that:
python
from functools import reduce print(reduce(lambda a, b: a * b, [], 1))
output
1