What's the function like sum() but for multiplication? product()?

Patrick McElhaney picture Patrick McElhaney · Feb 27, 2009 · Viewed 140.3k times · Source

Python's sum() function returns the sum of numbers in an iterable.

sum([3,4,5]) == 3 + 4 + 5 == 12

I'm looking for the function that returns the product instead.

somelib.somefunc([3,4,5]) == 3 * 4 * 5 == 60

I'm pretty sure such a function exists, but I can't find it.

Answer

ojrac picture ojrac · Feb 27, 2009

Actually, Guido vetoed the idea: http://bugs.python.org/issue1093

But, as noted in that issue, you can make one pretty easily:

from functools import reduce # Valid in Python 2.6+, required in Python 3
import operator

reduce(operator.mul, (3, 4, 5), 1)