Python math.prod() – Product of Elements in Iterable

Python math.prod()

math.prod(x) function returns the product of elements in the iterable x.

Syntax

The syntax to call prod() function is

math.prod(x, *, start=1)

where

ParameterRequiredDescription
xYesAn iterable.
*NoMore iterables.
startNoA numeric value.

math.prod() function is new in Python version 3.7.

Examples

1. Product of elements in a list

In the following program, we find the product of elements in a given list, using math.prod() function.

Python Program

import math

x = list([2.4, 5.1, 6.7])
result = math.prod(x)
print('prod(x) :', result)
Run Code Copy

Output

prod(x) : 82.008

2. Product of elements in a tuple

In the following program, we find the product of elements in a given tuple using math.prod() function.

Python Program

import math

x = tuple([2.4, 5.1])
result = math.prod(x)
print('prod(x) :', result)
Run Code Copy

Output

prod(x) : 12.239999999999998

3. Product of elements in an iterable, with a specific start value

In the following program, we find the product of elements in a given iterable with a specific start value of 2.

Python Program

import math

x = [5, 3]
result = math.prod(x, start = 2)
print('prod(x) :', result)
Run Code Copy

Output

prod(x) : 30

4. Product of elements in an empty iterable

Product of elements in iterable, when the iterable is empty.

Default start value of the product is 1. So, when there are no elements in the iterable, this start value is returned.

Python Program

import math

x = []
result = math.prod(x)
print('prod(x) :', result)
Run Code Copy

Output

prod(x) : 1

If we specify a value for start parameter, and the iterable is empty, this start value is returned by math.prod().

Python Program

import math

x = []
result = math.prod(x, start = 4)
print('prod(x) :', result)
Run Code Copy

Output

prod(x) : 4

5. Product of elements when there is infinity in the iterable

When there is one or more infinity values, and the rest float/integral values, in the iterable, math.prod() returns infinity.

Python Program

import math

x = [math.inf, 5, 3.2]
result = math.prod(x)
print('prod(x) :', result)
Run Code Copy

Output

prod(x) : inf

6. Product of elements when there is nan in the iterable

When there is at least one nan value in the iterable, then math.prod() returns nan.

Python Program

import math

x = [math.nan, 5, 3.2]
result = math.prod(x)
print('prod(x) :', result)
Run Code Copy

Output

prod(x) : nan

Summary

In this Python Math tutorial, we learned the syntax of, and examples for math.prod() function.

Related Tutorials

Code copied to clipboard successfully 👍