Python Glossary Русский

Python 3.8+mathterm

math.prod

aggregation

Returns the product of all the items of an iterable. Python 3.8+. math.prod([2, 3, 4]) → 24.

Syntax

math.prod(iterable, start=1)

For an empty iterable the result is start, i.e. 1 — a mathematical convention, not a bug; if your task needs 0 for empty input, check for it yourself. Note that start is multiplied in, not added, unlike in sum(). With ints the result stays exact at any size, but with floats rounding error accumulates, so compute factorials with math.factorial() instead.

Examples

import math
print(math.prod([1,2,3,4,5]))  # → 120
print(math.prod(range(1,6)))   # → 120 (= 5!)
print(math.prod([1.5, 2.0, 3.0]))  # → 9.0
print(math.prod([2]*10))       # → 1024 (2^10)
print(math.prod([], start=5))  # → 5
print(math.prod(range(1,8)))   # → 5040 (= 7!)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy