utterance
Yes, it's right. Guido rejected the idea of the prod () built-in function because he thought it was rarely needed.
Python update 3.8
In Python 3.8, prod () was added to the math module:
>>> from math import prod >>> prod(range(1, 11)) 3628800
Alternative with Reduce ()
As you suggested, it's easy to make your own using redu () and operator.mul () :
def prod(iterable): return reduce(operator.mul, iterable, 1) >>> prod(range(1, 5)) 24
In Python 3, the redu () function was moved to the functools module , so you need to add:
from functools import reduce
Special case: Factorials
As a note, the main motivating use of the prod () function is to calculate factorials. We already have support for this in the math module :
>>> import math >>> math.factorial(10) 3628800
Alternative with logarithms
If your data consists of floating point numbers, you can calculate the product using sum () with metrics and logarithms:
>>> from math import log, exp >>> data = [1.2, 1.5, 2.5, 0.9, 14.2, 3.8] >>> exp(sum(map(log, data))) 218.53799999999993 >>> 1.2 * 1.5 * 2.5 * 0.9 * 14.2 * 3.8 218.53799999999998
Raymond Hettinger Oct 30 '11 at 10:20 2011-10-30 22:20
source share