The reduce()
function is defined in the functools module.
Like the map and filter functions, the reduce()
function receives two arguments, a function and an iterable.
However, it doesn't return another iterable, instead it returns a single value.
The argument function is applied cumulatively to arguments in the list from left to right. The result of the function in the first call becomes the first argument and the third item in list becomes second. This is repeated until the list is exhausted.
In the example below, the add()
function is defined to return the sum of two numbers. This function is used in the reduce()
function along with a list of numbers 1,2,3, 4 and 5.
The output is a sum of all numbers 15.
>>> def add(a, b): return a + b >>> import functools >>> nums = [1, 2, 3, 4, 5] >>> total_sum = functools.reduce(add, nums) >>> total_sum 15 >>>
This article is contributed by Neha. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.