Reduce in Python

Python : Reduce

What is the Reduce Function in Python?

The reduce() function is a part of Python's built-in module functools. The reduce function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along.

Syntax for Reduce function in Python:

reduce(function, sequence[, initial])

reduce() function takes two arguments:

  • function: which performs the operations to each element of the list.
  • sequence: a list on which the operation needs to be performed.
  • Working: The function reduce() takes the first two elements of the sequence and applies the function on them, and then takes the result with the next element in the list and applies the function again. This process continues until it reaches the end of the sequence and produces a single accumulated result.

Example of reduce function in Python:

Let's write a code to find the product of all the elements of the list using reduce function.

from functools import reduce

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

# using reduce to compute product of all elements in the list
product = reduce((lambda x, y: x * y), lst)

print("Product of all elements in the list: ", product)

# Output: Product of all elements in the list: 120