The reduce()
function facilitates a functional approach to Python programming. It performs a rolling-computation as specified by the passed function to the neighboring elements, by taking a function and an iterable as arguments, and returns the final computed value.
Note: A rolling-computation is the one where we compute the required value by going through all of the data starting from the first value, where each new result depends on the last computed result of the previous data.
The reduce()
function computation is similar to a for-loop in Python, but being an in-built function, it’s much better and faster.
Here is the function signature for the reduce()
function in Python:
from functools import reduce # function signature for the reduce() method returned_value = reduce(function, iterable)
Note: The
reduce()
function resides in thefunctools
module which must be imported before the function is called.
As described above, the reduce()
function takes the following two arguments as input:
function
: A valid, pre-defined function. This is a lambda function in most cases.
iterable
: This is an iterable object (e.g. list, tuple, dictionary).
Returned: A single value gained as a result of applying the function to the iterable’s element.
Let’s take a look at a couple of examples of how the reduce()
method works:
from functools import reduce # Returns the sum of all the elements using `reduce` result = reduce((lambda a, b: a + b), [1, 2, 3, 4]) print(result)
from functools import reduce # Returns the sum of two elements def sumTwo(a,b): return a+b result = reduce(sumTwo, [1, 2, 3, 4]) print(result)
RELATED TAGS
View all Courses