Python reduce() function
In this article, we will learn the usage and syntax of the reduce() function in Python with examples.
In Python 3, this function is available in the functools module. This function is used when the program needs to call one function multiple times on a list of inputs. Using the reduce() function eliminates the need of creating a loop to traverse a list and apply the same function on each list item individually.
Syntax of reduce() function in Python
Syntax: reduce(function, list[, initial])
function: Calls the required function.
list: The list containing the values on which the required function is to be applied.
initial: Optional parameter to set the index of the list from which onwards the function is to be applied.
Below is a code to find out the sum of all the elements in the list, without the use of reduce().
#without reduce function List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sum = 0 for i in range (0, len(List)): sum = sum + List[i] print(sum)
And here is the same code, but with the use of reduce() function to get rid of the loop.
#with reduce function from functools import reduce def Add(a, b): return a+b List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sum = 0 sum = reduce(Add, List) print(sum)