PythonMastery
Python programs · Functions · beginner

map, filter and reduce in Python

Use map() to change every item, filter() to keep some items, and reduce() to combine items into one value. Also shows the list comprehension way.

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

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

Learn the idea: Lambda & Functional Programming, Comprehensions: Lists, Dicts, Sets, Generators