Should this function use reduce () or is there a more pythonic way?

If I have a value and a list of additional terms I want to multiply by the value:

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

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

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

Or is this the only way:

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

This is on Python 2.6.2. Thanks!

+4
source share
3 answers

Reduction 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 clearer than using reduce , especially if you think that many Python programmers have never seen reduce , and this name can convey little to people who actually see it for the first time.

Pythonic does not mean to write everything as understanding or always use a functional style, if possible. Python is a language with several paradigms and writing simple imperative code, when appropriate, Pythonic.

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

So, now let's reduce (). This is actually the one I always hated the most, because, in addition to a few examples involving + or *, almost every time I see a reduce () call with a non-trivial function argument, I need to grab the pen and chart paper, which actually served in this function before I understand what the reduce () method should do. Therefore, in my opinion, the applicability of reduce () is largely limited by associative operators, and in all other cases it is better to write the accumulation cycle explicitly.

There are not many associative operators. (These are X operators for which (a X b) X c is equal to a X (b X c).) I think this is roughly limited to +, *, &, |, ^, and shortcut and / or. We already have the amount (); I would love to trade reduce () for product (), so that takes care of the two most common uses. [...]

In Python 3, the abbreviation was moved to the functools module.

+7
source

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

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

n now 240. For more details, see the documents for the module.

+8
source

Another way:

 import operator n = reduce(operator.mul, terms, n) 
+2
source

All Articles