user1885116
user1885116

Reputation: 1797

Reduce - Python

I am trying to wrap my head around the following code. Am I right to deduce that a is mapped to (a+x) and x is an iterator that subsequently iterates over each element in the collection? (e.g. initially is zero, then 1, then 2)?

Any pointers much appreciated!

sum = reduce(lambda a, x: a + x, [0, 1, 2, 3, 4])
print sum #10

Upvotes: 2

Views: 421

Answers (3)

Mike Müller
Mike Müller

Reputation: 85442

This might help to imagine how it works:

def my_reduce(func, iterable):
    iterator = iter(iterable)
    res = next(iterator)
    for arg in iterator:
        res = func(res, arg)
    return res

>>> my_reduce(lambda a, x: a + x, [0, 1, 2, 3, 4])
10

Actually, there are two concepts here reduce and lambda. Instead of using lambda you can define a "normal" function:

def add(a, b):
    return a + b

Now, it might be a bit clearer:

>>> reduce(add, [0, 1, 2, 3, 4])
10 

Upvotes: 1

Harry Harrison
Harry Harrison

Reputation: 591

In Python, reduce applies a function to the first 2 items of a list, then applies the same function to the result with the 3rd item in the list, then applies the function to the result and the 4th item in the list and so on.

In your case:

 a = 0 + 1
 b = a + 2
 c = b + 3
 d = c + 4
 sum = d

Upvotes: 0

Falko
Falko

Reputation: 17867

Yes, you're right.

Just a minor correction: a is not initially zero. It's initialized with the first element of the collection. So the iteration starts with the second element.

From the documentation:

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).

So in your case reduce(lambda a, x: a + x, [0, 1, 2, 3, 4]) calculates ((((0+1)+2)+3)+4), which is 10.

Upvotes: 2

Related Questions