The reduce()
function from the functools
module is a higher-order function which applies a particular function cumulatively to all of the elements in an iterable.
The full syntax is as shown below:
reduce(func, iterable, initial = 0)
copy
func |
The function to be applied on the elements. This function should take two parameters, it will be called subsequently with the current iterable item and the accumulated value. |
iterable |
The sequence that is to be iterated over. This could be a list, dictionary, tuple, set, string, etc. |
initial |
This is the value that will be accumulated for the first item in the iterable. The default value for this is 0. |
The function applies the specified function accumulatively to the elements of the iterable and returns the accumulated value. The following shows the basic steps that are followed in the evaluation
- The
initial
value and the first element in the iterable are passed as arguments to the specified function, and the initial result is calculated. - The result is then passed back into the function as the accumulator, along with the second element in the iterable.
- This process is repeated with all remaining elements in the iterable, passing the result of the previous iteration as the accumulator.
- After all elements in the iterable have been processed, the final result is returned.
reduce() with Lambda functions
Lambda functions are particularly useful when working with higher-order functions. We can use them to create simple non-persistent functions.
Practical reduce() examples
We have already seen two practical cases of using the reduce()
function, i.e Summing the Items of a Container and getting product of the items in a container. The following examples demonstrated other practical cases to use the reduce()
function.
Flattening nested sequences
When you have a nested sequence, as in above example, performing the addition operation on each inner elements will result in a concatenation operation. The reduce() function performs this operation cumulatively resulting in all the inner sequences being concatenated into a single sequence. Of course the inner sequences will have to support concatenation operation and should obviously be of the same type.