Python reduce() function examples

Last updated on March 26, 2022 A Goodman Loading... Post a comment

In this article, you will learn about the syntax and walk through 3 examples of using the reduce() function in Python.


To use the reduce() function, you need to import it from the functools module as below:

from functools import reduce

The functools module comes along with Python installation.


value = reduce(function, sequence[, initial]) 

How does reduce() work?

  • When the initial value is provided, the function is called with the initial value and the first item from the sequence.
  • The 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.


Example 1: Find the largest and smallest number from a list

The code:

from functools import reduce

numbers = [100, 101, 99, 88, 143, 120, 94, 106]

def max(current_max, item):
    if(current_max < item):
        current_max = item
    return current_max

max_result = reduce(max, numbers)
print("Max:", max_result)

def min(current_min, item):
    if(current_min > item):
        current_min = item
    return current_min

min_result = reduce(min, numbers, 0)
print('Min:', min_result)


Max: 143
Min: 0

Example 2: Sum the numbers in a list

The code:

from functools import reduce

my_list = [1, 2, 3]

def accumulator(total, item):
    return total + item

result = reduce(accumulator, my_list, 0)



Using the lambda expression as the following gives the same result:

from functools import reduce

my_list = [1, 2, 3]
result = reduce(lambda total, item: total + item, my_list)

Example 3: Checks if all elements in a list satisfy a certain condition

This example will use the reduce () function to check if all of the people in a group are adults (over 18).

The code:

from functools import reduce

group_a = [
        "name": "Andy",
        "age": 41
        "name": "Ara",
        "age": 28
        "name": "Kindacode",
        "age": 4

group_b = [
        "name": "Bobby",
        "age": 32
        "name": "Ben",
        "age": 42

def check_age(current_status, person):
    return bool(current_status and person['age'] >= 18)

result_a = reduce(check_age, group_a, True)
print('All people in group A are adult:', result_a)

result_b = reduce(check_age, group_b, True)
print('All people in group B are adult:', result_b)


All people in group A are adult: False
All people in group B are adult: True


You have learned the fundamentals and gone through a few examples of the reduce() function. From now on, you get one more weapon to use in your programs. If you would like to learn more exciting stuff about Python, take a look at these articles:

You can also check out our Python category page for the latest tutorials and examples.

Notify of
Inline Feedbacks
View all comments

Related Articles