- reduce
reduce
In Python 2 it was still part of the language.
reduce(function, iterable[, initializer])
examples/functional/reduce.py
from functools import reduce numbers = [1, 2, 3, 4] print(reduce(lambda x,y: x+y, numbers)) # 10 = ((1+2)+3)+4 print(reduce(lambda x,y: x*y, numbers)) # 24 = ((1*2)*3)*4 print(reduce(lambda x,y: x/y, [8, 4, 2])) # 1.0 = (8/4)/2 print(reduce(lambda x,y: x+y, [2])) # 2 print(reduce(lambda x,y: x*y, [2])) # 2
10 24 1.0 2 2
The initializer is used as the 0th element returned by the iterable. It is mostly interesting in case the iterable is empty.