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.

4
  • 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? Commented May 3, 2014 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. Commented May 3, 2014 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 - artima.com/weblogs/viewpost.jsp?thread=98196 Commented May 3, 2014 at 23:46
  • possible duplicate of What's the Python function like sum() but for multiplication? Commented May 3, 2014 at 23:55

1 Answer 1

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


Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.