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
Advertisements