3

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.

Community
  • 1
  • 1
rookie
  • 2,783
  • 5
  • 29
  • 43
  • 1
    Could you be more specific? There's nothing magical about lambda: this is the same as `def f(x,y): return x*y` and then `reduce(f, [3,4,5])`. So is it really the behaviour of `reduce` which is confusing you? – DSM May 03 '14 at 23:36
  • @DSM: I was confused about `f(x,y)` works to compute the product (why we need `y`). I think @unutbu has explained this well with an example from the documentation. – rookie May 03 '14 at 23:41
  • You should replace lambdas with simple for-loop in most cases, they are much friendlier to read and there's no performance disadvantage. You don't need `reduce()` either - http://www.artima.com/weblogs/viewpost.jsp?thread=98196 – CodeManX May 03 '14 at 23:46
  • possible duplicate of [What's the Python function like sum() but for multiplication?](http://stackoverflow.com/questions/595374/whats-the-python-function-like-sum-but-for-multiplication) – CodeManX May 03 '14 at 23:55

1 Answers1

11

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).


unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677