math.sumprod(p, q) computes the sum of products from two iterables p and q, equivalent to sum(a * b for a, b in zip(p, q)) with enhanced accuracy for floats.
Added in Python 3.12, it keeps results as an exact int when both iterables hold integers and switches to accurate compensated arithmetic when floats are present.
math.sumprod() is a function in Python's standard math module: import it with import math and call math.sumprod(...), or import the name directly with from math import sumprod. Added in Python 3.12.
Syntax
Import math and pass two equal-length iterables (Python 3.12+).
python
import math
dot = math.sumprod(vec_a, vec_b)
Call
What it does
math.sumprod([1, 2, 3], [4, 5, 6])
Returns 32 (exact int: 4 + 10 + 18).
math.sumprod([0.5, 1.5], [2.0, 4.0])
Returns 7.0 (float).
math.sumprod([], [])
Returns 0.
math.sumprod([1, 2], ["a", "b"])
Multiplies pairs (note: non-numbers follow Python rules, though intended for numbers).
Requires Python 3.12 or newer; on Python 3.8–3.11, use hasattr(math, "sumprod") with a zip() fallback.
Function signatures
python
math.sumprod(p, q, /)
# added in Python 3.12; sum of products from p and q
Parameters
Parameter
Description
p
Required positional iterable of numeric factors.
q
Required positional iterable of matching numeric factors.
Return Value
Return Value
Description
int or float
int when all paired terms are integers (or empty); float when any float is involved.
Python Examples
Example 1 — Total an Invoice and Weighted Course Score (Python 3.12+)
Compute integer line-item totals and weighted float grades using math.sumprod().
Floats promote cleanly. Pairing float weights with exam scores calculates the weighted average 90.5 in one pass.
No temporary tuples. Unlike creating intermediate lists, math.sumprod() streams both iterables cleanly.
Example 2 — Compute Dot Products Safely Across Python Versions
Check hasattr(math, "sumprod") and fall back to zip() on Python 3.8 to 3.11.
python
import math
def dot_product(p, q):
if hasattr(math, "sumprod"):
return math.sumprod(p, q)
return sum(a * b for a, b in zip(p, q))
vec_u = [3, -2, 5]
vec_v = [4, 1, 2]
print("dot:", dot_product(vec_u, vec_v))
print("empty:", dot_product([], []))
Output
dot: 20
empty: 0
How It Works
Safe feature check. Uses fast C-level math.sumprod() on Python 3.12+ and portable generator sum on 3.8–3.11.
Exact signed integer dot product.3*4 + (-2)*1 + 5*2 sums to 20.
Empty sequences yield zero. Both branches return 0 for empty iterables.
Example 3 — Evaluate a Polynomial With Power Terms and Sumprod
Pair polynomial coefficients with powers of x via getattr fallback.
python
import math
sumprod_fn = getattr(
math,
"sumprod",
lambda p, q: sum(a * b for a, b in zip(p, q)),
)
coeffs = [2, 3, 5]
x = 4
powers = [x ** k for k in range(len(coeffs))]
print("2 + 3*4 + 5*16 =", sumprod_fn(coeffs, powers))