Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Friday, May 4, 2012

reduce method explained


numbers = [2, 5, 8, 9]

def iterative_sum(iterable):
    total = 0
    #iterative approach using state
    for ele in iterable:
        total += ele
    return total

def reduced_sum(iterable):
    return reduce(lambda x,y: x + y, iterable)   

print  iterative_sum(numbers)
print  reduced_sum(numbers)

24
24

So how does reduce actually work?  It starts by taking the first two elements (2 and 5) and apply the passed function or lambda expression on these 2 elements.  The result (7) is used with the 3rd element (8) which gives 15. 15 is used again together with 9 adding up to a total of 24. As the iterable is exhausted the reduce function returns the total of 24.

No comments:

Post a Comment