views:

102

answers:

3

If I have a value, and a list of additional terms I want multiplied to the value:

n = 10
terms = [1,2,3,4]

Is it possible to use a list comprehension to do something like this:

n *= (term for term in terms) #not working...

Or is the only way:

n *= reduce(lambda x,y: x*y, terms)

This is on Python 2.6.2. Thanks!

+6  A: 

Reduce is not the only way. You can also write it as a simple loop:

for term in terms:
    n *= term

I think this is much more clear than using reduce, especially when you consider that many Python programmers have never seen reduce and the name does little to convey to people who see it for the first time what it actually does.

Pythonic does not mean write everything as comprehensions or always use a functional style if possible. Python is a multi-paradigm language and writing simple imperative code when appropriate is Pythonic.

Guido van Rossum also doesn't want reduce in Python:

So now reduce(). This is actually the one I've always hated most, because, apart from a few examples involving + or *, almost every time I see a reduce() call with a non-trivial function argument, I need to grab pen and paper to diagram what's actually being fed into that function before I understand what the reduce() is supposed to do. So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it's better to write out the accumulation loop explicitly.

There aren't a whole lot of associative operators. (Those are operators X for which (a X b) X c equals a X (b X c).) I think it's just about limited to +, *, &, |, ^, and shortcut and/or. We already have sum(); I'd happily trade reduce() for product(), so that takes care of the two most common uses. [...]

In Python 3 reduce has been moved to the functools module.

Mark Byers
My thoughts exactly, just a minute quicker!
JoshD
I thought "pythonic" meant "write everything in one line"
Falmarri
Hmm, he's added `any()` and `all()` (which he proposed in the next paragraph after that quote), but never has added `product()`. Regardless of the ultimate fate of `reduce` (and I've never had any trouble reading it), `n *= product(terms)` is pretty clear. I think that deciding between a loop or a reduce call or whatever is less important than putting it in a well-named function.
Ken
Falmarri: No, you're thinking of APLic!
Ken
+7  A: 

reduce is the best way to do this IMO, but you don't have to use a lambda; instead, you can use the * operator directly:

import operator
n *= reduce(operator.mul, terms)

n is now 240. See the docs for the operator module for more info.

musicfreak
+2  A: 

Yet another way:

import operator
n = reduce(operator.mul, terms, n)
Bolo