Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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.

Yet another way:

import operator
n = reduce(operator.mul, terms, n)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top