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.

import functools

def add(a, b):
  return a + b

L = [1, 2, 3, 4, 5]

#get the sum of all elements in L
total_sum = functools.reduce(add, L )

print(total_sum)

The full syntax is as shown below:

reduce(func, iterable, initial = 0)
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.
import functools

def prod(a, b):
   return a * b

#a range of values from 1 to 10
L = [1, 2, 3, 4, 5]

product = functools.reduce(prod, L)

print(product)

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.

import functools

L = [1, 2, 3, 4, 5, 6, 7, 8, 9]

total_sum = functools.reduce(lambda a, b: a + b, L)
product = functools.reduce(lambda a, b: a * b, L)

print('sum: ', total_sum)
print('product: ', product)
 

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

import functools


nested = [[1, 2], [3, 4], [5, 6]]


flat = functools.reduce(lambda  x, y: x + y, nested )

print(flat)

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.

import functools


nested = [(1, 2), (3, 4), (5, 6)]


flat = functools.reduce(lambda  x, y: x + y, nested )

print(flat)

Reversing a string

import functools

string1 = "functools"
string2 = "Python"

reversed_string1 = functools.reduce(lambda x, y: y + x, string1)
reversed_string2 = functools.reduce(lambda x, y: y + x, string2)

print(reversed_string1)
print(reversed_string2)

Calculating the Factorial of a Number

from functools import reduce 

num = 5

factorial = reduce(lambda x,y : x * y, range(1, num + 1)) 

print(factorial) 

Finding the maximum or minimum element in a list

import functools

L = [8, 4, 6, 3, 5, 2, 7]

min_value = functools.reduce(lambda x, y: x if x < y else y, L)
max_value = functools.reduce(lambda x, y: x if x > y else y, L) 


print('min: ', min_value)
print('max: ', max_value)