Accumulating and reducing
List comprehensions and map
are very convenient tools when you need to apply a function to all elements of an iterable and get back the resulting values. But those are mostly meant to apply unary functions and keep a collection of the transformed values (such as add 1
to all numbers), but if you want to apply functions that should receive more than one element at the time, they don't fit very well.
The reduction and accumulation functions instead are meant to receive multiple values from the iterable and return a single value (in the case of reduction) or multiple values (in the case of accumulation).
How to do it...
The steps for this recipe are as follows:
- The most simple example of reduction is summing all items in an iterable:
>>> values = [ 1, 2, 3, 4, 5 ]
- This is something that can easily be done by
sum
, but for the sake of this example, we will usereduce
:
>>> import functools, operator
>>> functools.reduce(operator.add, values)
15
- If instead...