How to Use reduce Function in Python

reduce(func, seq) continually applies the function func() to the sequence seq. It returns a single value.

Working flow:

1.At first step, first two elements of sequence are picked and the result is obtained.

2.Next step is to apply the same function to the previously attained result and the number just succeeding the second element and the result is again stored.

3.This process continues till no more elements are left in the container.

4.The final returned result is returned and printed on console.

Here is an example:

items = [47,11,42,13]

def selectNumber(x,y):
    print x, y
    return x+y
squared2 = reduce(selectNumber, items)
print squared2

The result is:

47 11
58 42
100 13

The workflow of above example is:

We also can use lambda expression to replace function_to_apply.

squared2 = reduce(lambda x, y: x + y, items)
print squared2

the result is: