Python
About Lesson

Overview

The map()filter() and reduce() functions bring a bit of functional programming to Python. All three of these are convenience functions that can be replaced with List comprehensions or loops but provide a more elegant and short-hand approach to some problems

reduce() function

reduce() function work differently than map() and filter(). It does not return a new list based on the function and iterable we’ve passed. Instead, it returns a single value.

In Python3, reduce() isn’t a built-in function anymore, and it can be found in the functools module.

reduce() function works by calling the function we passed for the first two items in the sequence. The result returned by the function is used in another call to function alongside the next (third in this case), element.

Example

from functools import reduce

def add(x, y):
	return x + y

list = [2, 3, 4, 7];
print(reduce(add, list))

Output

16

It can be also done by using lambda function like map().