Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this function have to use reduce() or is there a more pythonic way?

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!

like image 256
bigjim Avatar asked Dec 03 '22 11:12

bigjim


1 Answers

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.

like image 98
Sasha Chedygov Avatar answered Jun 02 '23 22:06

Sasha Chedygov