Python - Combining Items in Iterables: reduce

Introduction

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:

Demo

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 )# from w  w  w .  ja  v a 2s . c om
d=reduce((lambda x, y: x * y), [1, 2, 3, 4]) 
print( d )

Result

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:

Demo

L = [1,2,3,4] 
res = L[0] # from   ww  w.ja  v a2 s .  c  o m
for x in L[1:]: 
    res = res + x 
print( res )

Result

The following function emulates most of the built-in's behavior and helps demystify its operation in general:

Demo

def myreduce(function, sequence): 
    tally = sequence[0] # from  ww  w  . j  ava 2s.c  o 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 )

Result

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.