Is there an embedded product () in Python?

I was looking through a tutorial and a book, but I cannot find mention of the built-in product function, i.e. same type as sum (), but I could not find anything like prod() .

Is the only way to find product items in a list by importing the mul() operator?

+72
python list product
Oct 30 '11 at 10:18
source share
4 answers

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 
+85
Oct 30 '11 at 10:20
source share

There is no product in Python, but you can define it as

 def product(iterable): return reduce(operator.mul, iterable, 1) 

Or, if you have NumPy, use numpy.product .

+19
Oct 30 '11 at 10:20
source share

Since the functools () function functools been ported to the python 3.0 functools module , you should use a different approach.

You can use functools.reduce() to access the function:

 product = functools.reduce(operator.mul, iterable, 1) 

Or, if you want to follow the spirit of the python command (which removed reduce() because they think that for will be more readable), do this with a loop:

 product = 1 for x in iterable: product *= x 
+12
Jun 21 '14 at 2:34
source share
 from numpy import multiply, product list1 = [2,2,2] list2 = [2,2,2] mult = 3 prod_of_lists = multiply(list1,list2) >>>[4,4,4] prod_of_list_by_mult = multiply(list1,mult) >>>[6,6,6] prod_of_single_array = product(list1) >>>8 

numpy has many really cool features for lists!

+7
Oct 30 '11 at 10:27
source share



All Articles