w3resource

What is the reduce function, and what does it do?

Python reduce() Function: Cumulative iteration for single values

Python's reduce() function is a higher-order function available in the functools module. It reduces an iterable (e.g., list, tuple) to a single accumulated value by applying a specified binary function (a function that takes two arguments). The function is repeatedly applied to pairs of items from left to right. The result of each step is used as the first argument for the next step.

Syntax:

functools.reduce(function, iterable, initial)

Arguments:

  • function: A binary function that takes two arguments and combines them.
  • iterable: A collection of items (such as a list, tuple) to whom the function will be applied.
  • initial (optional): An optional initial value. In the first call to the function, it serves as the first argument. The reduction starts with the second element of the iterable. If not provided, the first element of the iterable is used as the initial value.

The reduce() function performs a series of binary operations between elements of the iterable, cumulatively reducing the collection to a single result.

Example:

from functools import reduce
# Define a function to add two numbers
def product(x, y):
    return x * y
# Create a list of numbers
nums = [1, 2, 3, 4, 5]
# Use reduce() to multiply all the numbers in the list
result = reduce(product, nums)
print(result) 

Output:

120

In the above example, the product() function takes two arguments and returns their product. The reduce() function applies the product() function cumulatively to the "nums" list and reduces it to a single value, which is the product of all elements in the list.

Example: reduce() function with lambda functions

from functools import reduce
# Create a list of numbers
nums = [1, 2, 3, 4, 5]
# Use reduce() with a lambda function to 
#find the product of all numbers in the list
result = reduce(lambda x, y: x * y, nums)
print(result)  

Output:

120

When you need to perform cumulative operations on elements of a collection and produce a single final result, the reduce() function is particularly useful. Because it is cumulative, it may not be suitable for all scenarios, especially if the operation is not associative or commutative. In such cases, other functional programming tools like 'map' or 'filter' may be more appropriate.



Follow us on Facebook and Twitter for latest update.