Calmcode - lambda: reduce

Reduce

1 2 3 4 5

The functools library contains many items that allow you to make the most out of lambda functions. A common example is the reduce function. We'll show a demonstration below.

from functools import reduce

numbers = [1, 2, 3, 4, 5]

# sum via reduce
reduce(lambda x, y: x + y, numbers)
# prod via reduce
reduce(lambda x, y: x * y, numbers)

Note that reduce tells us what we are doing while the lambda function tells us how we are doing it.