## Reduce

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.

### Working :Β

• 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.

### Syntax :

``reduce(func, iterable[, initial])``

Where `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 `reduce()`: 1. `func` requires two arguments, the first of which is the first element in `iterable` (if `initial` is not supplied) and the second the second element in `iterable`. If `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.

Β

#### Program 1:

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)``````

#### Output :

``68``

As usual, it's all about iterations: `reduce` takes the first and second elements in `numbers` and passes them to `custom_sum` respectively. `custom_sum` computes their sum and returns it to `reduce`. `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.

#### Program 2:

Let's see what happens when I use the optional `initial` value.

``````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)``````

#### Output :

``78``

Β

The result, as you'll expect, is `78` because `reduce`, initially, uses `10` as the first argument to `custom_sum`.

source : geeksforgeeks.org , learnpython.org

Β