# Python reduce() function examples

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

## Overview

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.

Syntax:

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

## Examples

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

Output:

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

result = reduce(accumulator, my_list, 0)
print(result)``````

Output:

``6``

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)
print(result)``````

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

Output:

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

## Conclusion

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.

Subscribe
Notify of
Inline Feedbacks