prod() method in Python is used to calculate the product of all the elements present in the given iterable. Most of the built-in containers in Python like list, tuple are iterables. The iterable must contain numeric value else non-numeric types may be rejected.
In python, to multiply number, we will use the asterisk character ” * ” to multiply number. After writing the above code (how to multiply numbers in Python), Ones you will print “ number ” then the output will appear as a “ The product is: 60 ”.
The Python __mul__() method is called to implement the arithmetic multiplication operation * . For example to evaluate the expression x * y , Python attempts to call x. __mul__(y) . We call this a “Dunder Method” for “Double Underscore Method” (also called “magic method”).
Product is when you multiply two numbers, the sum is when you add them. The PRODUCT is always the answer to a MULTIPLICATION.
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)
In Python 3.8, the prod function was added to the math module. See: math.prod().
The function you're looking for would be called prod() or product() but Python doesn't have that function. So, you need to write your own (which is easy).
Yes, that's right. Guido rejected the idea for a built-in prod() function because he thought it was rarely needed.
As you suggested, it is not hard to make your own using reduce() and operator.mul():
from functools import reduce # Required in Python 3
import operator
def prod(iterable):
return reduce(operator.mul, iterable, 1)
>>> prod(range(1, 5))
24
Note, in Python 3, the reduce() function was moved to the functools module.
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:
>>> import math
>>> math.factorial(10)
3628800
If your data consists of floats, you can compute a product using sum() with exponents 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
Note, the use of log() requires that all the inputs are positive.
There's a prod()
in numpy that does what you're asking for.
There isn't one built in, but it's simple to roll your own, as demonstrated here:
import operator
def prod(factors):
return reduce(operator.mul, factors, 1)
See answers to this question:
Which Python module is suitable for data manipulation in a list?
Numeric.product
( or
reduce(lambda x,y:x*y,[3,4,5])
)
Use this
def prod(iterable):
p = 1
for n in iterable:
p *= n
return p
Since there's no built-in prod
function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With