Skip to main content
Python reduce function With Example

Python reduce() Function With Example

in this post, we’ll see how to use reduce() function in python to process a list. This function is used to apply a function to all of the list elements that is supplied as an argument. This function is defined under “functools” module.

Reduce() comes in helpful when you need to apply a function to an iterable and reduce it to a single cumulative value.

According to the documentation for reduce(), the function has the following signature:

reduce(func, iterable[, initial])

The reduce function takes three arguments::

func: This is the cumulative function that each element in the iterable is applied to.
iterable: Any python iterable data structure
initial: this is the optional value and acts as a default when the iterable is empty.

Python reduce() with inbuilt function

Let’s take an example that’ll return the sum of the list number. We’ll use the operator inbuild add() method that will return the sum up the all numbers.

import operator 
import functools 
sequence = [2,8,9,10,16] 
sum = functools.reduce( operator.add, sequence,0) 

print(sum)

Output:

45

in the above code, We are passing operator.add() function and sequence as arguments, You get an output that shows all the operations that reduce() performs to come up with a final result of 45. The operations are equivalent to ((((2 + 8) + 9) + 10) + 16) = 45.

Python reduce() with Custom function

Let’s take a user-defined function(custom method) as an argument with reduce() function.

import functools 
def my_add(a, b):
   result = a + b
   return result
sequence = [2,8,9,10,17] 
sum = functools.reduce( my_add, sequence,0) 

print(sum)

Output:

46

Python reduce() method with initial value

Let’s pass some initial value to the reduce function, I am passing 10 as the initial value to the above code.

import functools 
def my_add(a, b):
   result = a + b
   return result
sequence = [2,8,9,10,17] 
sum = functools.reduce( my_add, sequence,10) 

print(sum)

Output:

56

As you can see output, the 10 value has been added to the sum of the iterable.

Leave a Reply

Your email address will not be published. Required fields are marked *