Try it here

Python - Reduce Function


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

Writer profile pic

Neha on Sep 26, 2020 at 01:09 am

This article is contributed by Neha. If you like and would like to contribute, you can write your article here or mail your article to . See your article appearing on the main page and help others to learn.

Post Comment

Comments( 0)


Forgot Password

Please enter your email address below and we will send you information to change your password.