man python/reduce-prod-and-ints

Multiplying a list in Python: loops, reduce, operator.mul and math.prod

lib / Python 13 mindraft

checked against: CPython 3.15.2

Python has at least four ways to multiply the numbers in a list. A for loop with result *= n. functools.reduce with a lambda. reduce with operator.mul. And math.prod. They all return the same number. Are they really different?

They are. Each runs a different amount of C, creates a different number of Python frames, and handles a growing product its own way. This article reads the CPython 3.15.2 source for each and times them. All timings come from an Apple M2 Pro. The interpreters are separate builds (Apple’s 3.9.6, a uv 3.12.16, Homebrew 3.13.3, 3.14.6 and 3.15.2), so cross-version numbers compare builds as well as versions.

The loop: six instructions per item, specialised

def product(top):
    result = 1
    for n in top:
        result *= n
    return result

After 1,000 calls with [3, 5, 7], dis.dis(product, adaptive=True) on 3.15.2 shows the instructions the interpreter has rewritten for the types it saw (excerpt):

  3           LOAD_SMALL_INT           1
              STORE_FAST               1 (result)

  4           LOAD_FAST                0 (top)
              GET_ITER_VIRTUAL         0
      L1:     FOR_ITER_LIST           11 (to L2)
              STORE_FAST               2 (n)

  5           LOAD_FAST_BORROW_LOAD_FAST_BORROW 18 (result, n)
              BINARY_OP_MULTIPLY_INT  18 (*=)
              STORE_FAST               1 (result)
              JUMP_BACKWARD_NO_JIT    13 (to L1)

Before warm-up the same slots read GET_ITER, FOR_ITER and BINARY_OP 18 (*=). Each item runs six instructions, from FOR_ITER_LIST to JUMP_BACKWARD_NO_JIT. The specialisation depends on the data. I ran the same function 1,000 times on [3, 5, 7], [1.5, 2.5, 0.5] and [2**100, 3**80, 5**60], each time with a fresh copy (types.FunctionType(product.__code__.replace(), {})):

small ints ['FOR_ITER_LIST', 'BINARY_OP_MULTIPLY_INT']
floats     ['FOR_ITER_LIST', 'BINARY_OP_MULTIPLY_FLOAT']
big ints   ['FOR_ITER_LIST', 'BINARY_OP']

BINARY_OP_MULTIPLY_INT is guarded. Both operands must be exact ints and “compact” (_PyLong_CheckExactAndCompact, bytecodes.c lines 635-643). It multiplies the two values as C integers and exits back to the generic path if the result is not compact (EXIT_IF(PyStackRef_IsNull(res))). In longobject.c, medium_from_stwodigits returns NULL when is_medium_int fails, that is, when the product needs more than one 30-bit digit. So the fast path covers products under 2**30 in magnitude. A list of 100-bit ints never qualifies, and the instruction stays a plain BINARY_OP.

functools.reduce: a C loop that calls you back

functools.reduce is defined twice. Lib/functools.py has a pure-Python version (a for loop calling function(value, element)), and near the end of the file it is replaced by from _functools import reduce. On 3.15.2, functools.reduce is a builtin_function_or_method.

The C version in Modules/_functoolsmodule.c is short. It builds one 2-tuple, and for each item it puts the running result and the next item into that tuple and calls PyObject_Call(func, args, NULL). If nobody else kept a reference to the tuple (_PyObject_IsUniquelyReferenced(args)), it reuses it for the next item instead of allocating a new one.

What PyObject_Call does next depends on func.

operator.mul is C. Lib/operator.py defines a Python mul, then from _operator import * replaces it with the C one, and _operator_mul_impl is one line, return PyNumber_Multiply(a, b);.

A lambda is a Python function. PyObject_Call reaches _PyFunction_Vectorcall, which calls _PyEval_Vector, which pushes a new interpreter frame with _PyEvalFramePushAndInit. One frame per item. A profile hook makes this visible. The sys.setprofile docs define a call event as “A function is called (or some other code block entered)”, and C functions get separate c_call events. This hook records only call:

def python_frames(fn):
    names = []
    def hook(frame, event, arg):
        if event == "call":
            names.append(frame.f_code.co_qualname)
    sys.setprofile(hook)
    fn()
    sys.setprofile(None)
    return names

top = [57, 43, 76]
python_frames(lambda: reduce(lambda x, y: x * y, top))
python_frames(lambda: reduce(operator.mul, top))
lambda:       ['<lambda>', '<lambda>.<locals>.<lambda>', '<lambda>.<locals>.<lambda>']
operator.mul: ['<lambda>']

The first entry in each list is the outer test lambda. The lambda version adds two frames, one per multiplication. The operator.mul version adds none.

The pure-Python reduce can beat the C one

I loaded a second copy of functools with sys.modules["_functools"] = None, which makes the C import fail and leaves the Python reduce in place. Then I timed red(fn, [1, -1] * 500) for both versions with both functions:

Python 3.9.6
C reduce       operator.mul    11.94 us
C reduce       lambda          33.76 us
Python reduce  operator.mul    25.15 us
Python reduce  lambda          57.34 us

Python 3.12.16
C reduce       operator.mul     9.27 us
C reduce       lambda          23.08 us
Python reduce  operator.mul    13.51 us
Python reduce  lambda          22.83 us

Python 3.15.2
C reduce       operator.mul    10.59 us
C reduce       lambda          25.06 us
Python reduce  operator.mul    17.44 us
Python reduce  lambda          21.08 us

On 3.9 the C version wins by a wide margin either way. On 3.12 the two tie with a lambda, and on 3.15 the Python version is faster with a lambda. This is consistent with a change described in the 3.11 What’s New. Since 3.11, when Python code calls a Python function, CPython “sets up a new frame, and ‘jumps’ to the new code inside the new frame”, avoiding the C evaluation function. The C reduce cannot use that shortcut, because it calls the lambda from C through PyObject_Call. In the Python version the call site specialises. After warm-up, dis shows CALL_PY_EXACT_ARGS on the line value = function(value, element).

math.prod: the product stays in a C long

math.prod(iterable, *, start=1) is in Modules/mathmodule.c and has three phases.

  1. Int phase. If start is an exact int that fits in a C long, the running product is kept as a C long. Each item that is an exact int fitting in a long is multiplied in C, after a check by _check_long_mult_overflow. No Python object is created per item. The check computes the product both as a long and as a double and accepts the long result when the two differ by at most 1/32 of the product.
  2. Float phase. If the result is an exact float, the product is kept as a C double. Floats and ints that fit in a long are multiplied in directly.
  3. Generic phase. Everything else goes through PyNumber_Multiply, one item at a time.

The phases run in that order and never go back. A list of floats with the default start=1 enters the int phase, hits the first float, does one generic multiply (1 * x gives a float), and then the float phase takes over. An int product that overflows a long falls into the generic phase and stays there for the rest of the iterable. On this Mac a C long is 8 bytes (struct.calcsize("l")), so this fast path covers far more range than the loop’s 30-bit compact path.

Timings

I timed each version with timeit (autorange, best of 7) on five inputs, built after random.seed(2026): [57, 43, 76], random.choice((1, -1)), random.randint(1, 9), random.uniform(0.5, 1.5), and random.getrandbits(99) | (1 << 99), 1,000 of each. Each cell times timeit.Timer(lambda: f(data)), where f wraps one version, so the 3-item row is mostly call overhead. Python 3.15.2 on an Apple M2 Pro:

dataloopreduce + lambdareduce + operator.mulmath.prod
3 ints [57, 43, 76]0.07 us0.17 us0.10 us0.08 us
1000 ints, each +1 or -111.33 us25.10 us10.62 us3.99 us
1000 ints in 1..970.16 us91.74 us69.75 us65.84 us
1000 floats in 0.5..1.510.35 us28.53 us14.62 us3.12 us
1000 100-bit ints10.87 ms10.84 ms10.85 ms10.73 ms

The +1/-1 row is the one where the product never leaves a machine word. That is where math.prod is fastest, about 2.8 times quicker than the loop, and where the lambda is slowest relative to the others.

The 1..9 row looks like a small-int case and is not one. The running product passes 30 bits at item 15 and 63 bits at item 28, and ends at 2,006 bits. From item 28 on, every version is multiplying a growing big int by a one-digit int, and the gaps narrow to the cost of the lambda calls.

The 100-bit row is pure big-int arithmetic. The result has 99,558 bits, and the choice of loop no longer matters.

For the 3-item case I also timed the bare statements with python -m timeit -s "import math, operator; from functools import reduce; top = [57, 43, 76]" ...:

statement3.9.63.15.2
r = 1 / for n in top: r *= n85 ns37.4 ns
reduce(lambda x, y: x * y, top)185 ns140 ns
reduce(operator.mul, top)119 ns74.4 ns
math.prod(top)78.4 ns52.9 ns

For three items on 3.15, the plain loop is the fastest of the four. The lambda line also runs MAKE_FUNCTION every time, creating a new function object.

Across versions, the +1/-1 and float rows changed the most:

buildloop ±1prod ±1loop floatsprod floats
3.9.619.04 us7.51 us18.44 us2.85 us
3.12.1610.25 us3.06 us10.59 us2.47 us
3.13.310.73 us3.67 us10.81 us2.76 us
3.14.614.48 us3.97 us18.41 us2.81 us
3.15.211.33 us3.99 us10.35 us3.12 us

The loop roughly halved between 3.9 and 3.12. The specialising interpreter arrived in between, in 3.11, but I had no 3.10 or 3.11 build to pin it down. The 3.14.6 loop numbers reproduced on a second run on an idle machine. I have not traced their cause, and this table cannot separate the version from the build.

When the product gets big: Python ints

A Python int is an array of digits. On this build sys.int_info reports bits_per_digit=30, sizeof_digit=4. Include/cpython/longintrepr.h allows 30-bit digits in a uint32_t or 15-bit digits in an unsigned short, chosen at build time. The digit count, the sign and a small-int flag share one lv_tag field. An int is “compact” when it has at most one digit, which is the condition the specialised bytecode checks.

Values from -5 to 1024 are preallocated singletons in 3.15. Include/internal/pycore_runtime_structs.h sets _PY_NSMALLPOSINTS to 1025 and _PY_NSMALLNEGINTS to 5. At v3.14.6 the positive bound was 257. A check of int(str(n)) is int(str(n)) for n in -6, -5, 256, 257, 1024 and 1025 agrees:

3.9.6 [-5, 256]
3.12.16 [-5, 256]
3.13.3 [-5, 256]
3.14.6 [-5, 256]
3.15.2 [-5, 256, 257, 1024]

Multiplication starts in long_mul. If both operands are compact, it multiplies them as C integers. Otherwise it calls k_mul. That function uses schoolbook multiplication (x_mul) “unless both operands contain more than KARATSUBA_CUTOFF digits”, and KARATSUBA_CUTOFF is 70, so about 2,100 bits. Squaring (a * a) uses a cutoff of 140 and a dedicated loop inside x_mul that skips duplicate partial products. When the smaller operand is above the cutoff and at most half the size of the other, k_lopsided_mul cuts the bigger one into slices the size of the smaller one.

Schoolbook on two k-digit numbers costs about k² digit multiplications. Karatsuba replaces one product of size k with three of size k/2, so doubling k should cost about 3 times as much instead of 4. I timed a * b for two random numbers of equal size on 3.15.2:

 digits    bits   a*b (us)  ratio vs half
     35    1050      1.253
     70    2100      5.854           4.67
    140    4200     19.628           3.35
    280    8400     53.817           2.74
    560   16800    173.143           3.22
   1120   33600    513.617           2.97
   2240   67200   1552.230           3.02
   4480  134400   4638.332           2.99

Above the cutoff the ratio settles near 3. Below it the data is noisy. From 35 to 70 digits cost 4.67x here, but an earlier run measured 4.39x from 16 to 32 digits and 3.32x from 32 to 64, all schoolbook.

This explains the 100-bit row above. A 100-bit int is 4 digits. Every step of a left-to-right product multiplies a large number by a 4-digit one, k_mul sees the smaller side is under the cutoff, and everything runs as schoolbook. Multiplying in pairs instead puts large numbers on both sides near the top of the tree:

def tree_prod(xs):
    while len(xs) > 1:
        pairs = [a * b for a, b in zip(xs[::2], xs[1::2])]
        if len(xs) % 2:
            pairs.append(xs[-1])
        xs = pairs
    return xs[0]
Python 3.15.2 | result bits: 99558
math.prod    10.801 ms
tree_prod     2.523 ms

Same result, about four times faster, from pure Python. All four versions above multiply left to right and cannot do this.

Parsing: split() and map

str.split() with no argument has its own code path. In Objects/unicodeobject.c, split() dispatches on the string’s storage kind to one of four *_split_whitespace functions generated from Objects/stringlib/split.h, asciilib_split_whitespace for ASCII text. It scans for runs of whitespace, slices out each word, and preallocates up to 12 list slots (MAX_PREALLOC). A run of whitespace is one separator and a trailing newline adds nothing, so on a 1,000-line test input text.split() ends with a number while text.split("\n") ends with ''.

map in Python 3 is lazy. The 3.0 What’s New says map() and filter() “return iterators”. map_next in Python/bltinmodule.c pulls one item from each source iterator and calls the function on them, one result per next(). Errors show up only when the bad item is reached. For m = map(int, ["57", "43", "oops"]), then next(m) three times:

map created, nothing parsed yet
57 43
ValueError on third item: invalid literal for int() with base 10: 'oops'

Timing each expression on that input (3,000 characters), on 3.15.2:

text.split()                      15.45 us
text.split('\n')                  15.19 us
text.splitlines()                 15.23 us
map(int, text.split())            15.61 us
list(map(int, text.split()))      41.63 us

Building the map object costs almost nothing. The int() calls cost about 26 us for 1,000 numbers, more than the split, and run when something consumes the map.

Curious facts

  • math.prod(["ab", 3]) returns 'ababab'. The default start=1 times "ab" is "ab", and the generic phase accepts any type that supports *. The docs say it “may reject non-numeric types”. It does not have to.
  • math.prod([]) is 1. reduce(lambda x, y: x * y, []) raises TypeError: reduce() of empty iterable with no initial value.
  • In 3.15 functools._initial_missing is created with the new sentinel built-in (PEP 661), so print(functools._initial_missing) prints _initial_missing.
  • 2**30 is already a two-digit int (31 bits), so a loop over [2**30, 2**30] stays on plain BINARY_OP after 1,000 calls. math.prod keeps the same product, 2**60, in a C long.

Version history

  • 3.0: reduce() removed from builtins. What’s New 3.0: “Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable.” The same release made map() return an iterator.
  • 3.8: math.prod() added, “analogous function to sum()” with a start value (bpo-35606).
  • 3.11: the specialising adaptive interpreter (PEP 659), with fast paths for binary multiply on int and float, and inlined Python-to-Python calls.
  • 3.14: initial in reduce() can be passed as a keyword (gh-125916). Calling the Python implementation of reduce() with function or sequence as keywords is deprecated. 3.14 also added the LOAD_SMALL_INT and LOAD_FAST_BORROW_LOAD_FAST_BORROW opcodes seen in the dis output above.
  • 3.15: the small-int cache grows from -5..256 to -5..1024 (source and experiment above; I did not find it in What’s New). The sentinel built-in arrives (PEP 661).

Sources

CPython v3.15.2 source:

Documentation:

ls python/