search

What is the use of the "reduce" function in Python?

The **reduce** function is a part of the **functools** module in Python and is used to apply a particular function to elements of a sequence (e.g., a list), in a cumulative way. The **reduce** function takes two arguments: a function and a sequence (e.g., a list). The function is applied cumulatively to the elements of the sequence, starting with the first two elements, then to the result and the next element, and so on, until all elements have been processed. The final result is the cumulative result of all the function calls.

For example, if you want to find the product of all the elements in a list, you can use the **reduce** function and the **operator.mul** function:

from functools import reduce
import operator

lst = [1, 2, 3, 4, 5]
product = reduce(operator.mul, lst)
print(product)

Output:

120

Related Questions You Might Be Interested