reduce function selects an iterable's items by applying functions to item pairs.
The functional reduce accepts an iterable to process, it returns a single result.
Here are two reduce calls that compute the sum and product of the items in a list:
from functools import reduce # Import in 3.X, not in 2.X d=reduce((lambda x, y: x + y), [1, 2, 3, 4]) print( d )# www. j a v a 2s . c o m d=reduce((lambda x, y: x * y), [1, 2, 3, 4]) print( d )
At each step, reduce passes the current sum or product, along with the next item from the list, to the passed.
By default, the first item in the sequence initializes the starting value.
You can implement the reduce with a loop:
L = [1,2,3,4] res = L # w w w . j a v a2 s .c om for x in L[1:]: res = res + x print( res )
The following function emulates most of the built-in's behavior and helps demystify its operation in general:
def myreduce(function, sequence): tally = sequence # ww w . j a v a 2 s . co m for next in sequence[1:]: tally = function(tally, next) return tally d=myreduce((lambda x, y: x + y), [1, 2, 3, 4, 5]) print( d ) d=myreduce((lambda x, y: x * y), [1, 2, 3, 4, 5]) print( d )
reduce function allows an optional third argument placed before the items in the sequence to serve as a default result when the sequence is empty.