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