This question already has an answer here:
I've been looking through a tutorial and book but I can find no mention of a built in product function i.e. of the same type as sum(), but I could not find anything such as prod()
.
Is the only way I could find the product of items in a list by importing the mul()
operator?
Since the reduce() function has been moved to the module
functools
python 3.0, you have to take a different approach.You can use
functools.reduce()
to access the function:Or, if you want to follow the spirit of the python-team (which removed
reduce()
because they thinkfor
would be more readable), do it with a loop:numpy has many really cool functions for lists!
Pronouncement
Yes, that's right. Guido rejected the idea for a built-in prod() function because he thought it was rarely needed.
Alternative with reduce()
As you suggested, it is not hard to make your own using reduce() and operator.mul():
In Python 3, the reduce() function was moved to the functools module, so you would need to add:
Specific case: Factorials
As a side note, the primary motivating use case for prod() is to compute factorials. We already have support for that in the math module:
Alternative with logarithms
If your data consists of floats, you can compute a product using sum() with exponents and logarithms:
There is no
product
in Python, but you can define it asOr, if you have NumPy, use
numpy.product
.