The reduce(fun,seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along.This function is defined in “functools” module.
- At first step, first two elements of sequence are picked and the result is obtained.
- Next step is to apply the same function to the previously attained result and the number just succeeding the second element and the result is again stored.
- This process continues till no more elements are left in the container.
- The final returned result is returned and printed on console.
reduce(func, iterable[, initial])
func is the function on which each element in the
iterable gets cumulatively applied to, and
initial is the optional value that gets placed before the elements of the iterable in the calculation, and serves as a default when the iterable is empty. The following should be noted about
func requires two arguments, the first of which is the first element in
initial is not supplied) and the second the second element in
initial is supplied, then it becomes the first argument to
func and the first element in
iterable becomes the second element. 2.
reduce "reduces" (I know, forgive me)
iterable into a single value.
Let's create a example of Python's built-in
sum() function. The
sum() function returns the sum of all the items in the iterable passed to it.
from functools import reduce numbers = [3, 4, 6, 9, 34, 12] def custom_sum(first, second): return first + second result = reduce(custom_sum, numbers) print(result)
As usual, it's all about iterations:
reduce takes the first and second elements in
numbers and passes them to
custom_sum computes their sum and returns it to
reduce then takes that result and applies it as the first element to
custom_sum and takes the next element (third) in
numbers as the second element to
custom_sum. It does this continuously (cumulatively) until
numbers is exhausted.
Let's see what happens when I use the optional
from functools import reduce numbers = [3, 4, 6, 9, 34, 12] def custom_sum(first, second): return first + second result = reduce(custom_sum, numbers, 10) print(result)
The result, as you'll expect, is
reduce, initially, uses
10 as the first argument to