Python math.prod() Method
The Python math.prod() method is used to calculate the product of all elements in a given iterable. Mathematically, it is denoted as −
prod(x1, x2, x3, ..., xn) = x1 × x2 × x3 × ... × xn
For example, if we have a list "[2, 3, 4, 5]", the "math.prod([2, 3, 4, 5])" method call will return 2 × 3 × 4 × 5 = 120.
Syntax
Following is the basic syntax of the Python math.prod() method −
math.prod(iterable, *, start=1)
Parameters
This method accepts the following parameters −
iterable − It is the iterable (such as a list, tuple, or generator) whose element's product is to be calculated.
start (optional) − It specifies the starting value for the product. It's default value is 1.
Return Value
The method returns the product of all the elements in the iterable.
Example 1
In the following example, we are calculating the product of all elements in the list "[1, 2, 3, 4, 5]" −
import math
numbers = [1, 2, 3, 4, 5]
result = math.prod(numbers)
print("The result obtained is:",result)
Output
The output obtained is as follows −
The result obtained is: 120
Example 2
Here, we are using a generator expression to generate numbers from "1" to "5". We then calculate the product of these numbers −
import math
numbers = (i for i in range(1, 6))
result = math.prod(numbers)
print("The result obtained is:",result)
Output
Following is the output of the above code −
The result obtained is: 120
Example 3
Now, we are calculating the product of all the fractional elements in the list "[0.5, 0.25, 0.1]" −
import math
numbers = [0.5, 0.25, 0.1]
result = math.prod(numbers)
print("The result obtained is:",result)
Output
We get the output as shown below −
The result obtained is: 0.0125
Example 4
In this example, we are calculating the product of an empty list −
import math
result = math.prod([])
print("The result obtained is:",result)
Output
The result produced is as shown below −
The result obtained is: 1
python_maths.htm