Question

While looking up concise ways to calculate the product of a list, I was a little confused by this response. Here's the code in question:

reduce(lambda x,y:x*y,[3,4,5])

Can someone explain why this works? I'm familiar with using lambda expressions involving one variable (e.g. when using a custom compare function for sorting) but am confused why and how this works.

Was it helpful?

Solution

lambda x,y: x*y is an anonymous function otherwise equivalent to

def foo(x, y):
    return x*y

To understand its use in reduce(lambda ...), consider the example from the docs:

reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).

Similarly, reduce(lambda x,y:x*y,[3,4,5]) calculates ((3*4)*5).


Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top