How to Use the Python reduce() Function

09/11/2021

Contents

In this article, you will learn how to use the Python reduce() function.

Python reduce() Function

The reduce() function is a built-in function in Python that is used to apply a function to a sequence of values, reducing them to a single value. The reduce() function takes two arguments: a function and an iterable. The function takes two arguments, and the iterable can be any sequence type (e.g., list, tuple, set, etc.). Here’s an example of how to use the reduce() function in Python:

from functools import reduce

# Example 1: Summing up the values in a list
my_list = [1, 2, 3, 4, 5]
sum_of_list = reduce(lambda x, y: x + y, my_list)
print(sum_of_list) # Output: 15

# Example 2: Finding the maximum value in a list
my_list = [1, 4, 2, 7, 5]
max_value = reduce(lambda x, y: x if x > y else y, my_list)
print(max_value) # Output: 7

# Example 3: Concatenating strings in a list
my_list = ['Hello', ' ', 'world', '!']
concatenated_string = reduce(lambda x, y: x + y, my_list)
print(concatenated_string) # Output: Hello world!

In Example 1, the reduce() function is used to sum up the values in a list. The lambda function takes two arguments x and y and returns their sum, which is then used as the first argument in the next call to the function, along with the next value from the list. This process is repeated until all values in the list have been processed.

In Example 2, the reduce() function is used to find the maximum value in a list. The lambda function takes two arguments x and y and returns the greater of the two values. This process is repeated until the maximum value in the list has been found.

In Example 3, the reduce() function is used to concatenate the strings in a list. The lambda function takes two arguments x and y and returns their concatenation. This process is repeated until all strings in the list have been concatenated into a single string.

Note that in Python 3, the reduce() function has been moved from the built-in namespace to the functools module, so you need to import it first before you can use it.