man python/reduce-prod-and-ints
Multiplying a list in Python: loops, reduce, operator.mul and math.prod
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.
- Int phase. If
startis an exact int that fits in a Clong, the running product is kept as a Clong. Each item that is an exact int fitting in alongis 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 alongand as adoubleand accepts thelongresult when the two differ by at most 1/32 of the product. - Float phase. If the result is an exact float, the product is kept as a C
double. Floats and ints that fit in alongare multiplied in directly. - 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:
| data | loop | reduce + lambda | reduce + operator.mul | math.prod |
|---|---|---|---|---|
3 ints [57, 43, 76] | 0.07 us | 0.17 us | 0.10 us | 0.08 us |
| 1000 ints, each +1 or -1 | 11.33 us | 25.10 us | 10.62 us | 3.99 us |
| 1000 ints in 1..9 | 70.16 us | 91.74 us | 69.75 us | 65.84 us |
| 1000 floats in 0.5..1.5 | 10.35 us | 28.53 us | 14.62 us | 3.12 us |
| 1000 100-bit ints | 10.87 ms | 10.84 ms | 10.85 ms | 10.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]" ...:
| statement | 3.9.6 | 3.15.2 |
|---|---|---|
r = 1 / for n in top: r *= n | 85 ns | 37.4 ns |
reduce(lambda x, y: x * y, top) | 185 ns | 140 ns |
reduce(operator.mul, top) | 119 ns | 74.4 ns |
math.prod(top) | 78.4 ns | 52.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:
| build | loop ±1 | prod ±1 | loop floats | prod floats |
|---|---|---|---|---|
| 3.9.6 | 19.04 us | 7.51 us | 18.44 us | 2.85 us |
| 3.12.16 | 10.25 us | 3.06 us | 10.59 us | 2.47 us |
| 3.13.3 | 10.73 us | 3.67 us | 10.81 us | 2.76 us |
| 3.14.6 | 14.48 us | 3.97 us | 18.41 us | 2.81 us |
| 3.15.2 | 11.33 us | 3.99 us | 10.35 us | 3.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 defaultstart=1times"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([])is1.reduce(lambda x, y: x * y, [])raisesTypeError: reduce() of empty iterable with no initial value.- In 3.15
functools._initial_missingis created with the newsentinelbuilt-in (PEP 661), soprint(functools._initial_missing)prints_initial_missing. 2**30is already a two-digit int (31 bits), so a loop over[2**30, 2**30]stays on plainBINARY_OPafter 1,000 calls.math.prodkeeps the same product, 2**60, in a Clong.
Version history
- 3.0:
reduce()removed from builtins. What’s New 3.0: “Usefunctools.reduce()if you really need it; however, 99 percent of the time an explicitforloop is more readable.” The same release mademap()return an iterator. - 3.8:
math.prod()added, “analogous function tosum()” with astartvalue (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:
initialinreduce()can be passed as a keyword (gh-125916). Calling the Python implementation ofreduce()withfunctionorsequenceas keywords is deprecated. 3.14 also added theLOAD_SMALL_INTandLOAD_FAST_BORROW_LOAD_FAST_BORROWopcodes seen in thedisoutput 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
sentinelbuilt-in arrives (PEP 661).
Sources
CPython v3.15.2 source:
- Modules/_functoolsmodule.c L1066-L1155: C
reduce, tuple reuse at L1112, call at L1132 - Lib/functools.py L235-L265: pure-Python
reduce; L1201-L1208: import of the C version - Lib/operator.py L112-L114 and L421-L424; Modules/_operator.c L94-L98
- Objects/call.c L333-L366 and L402-L418; Python/ceval.c L2140-L2174
- Modules/mathmodule.c L2631-L2677: overflow check; L2681-L2833:
math.prod, int phase at L2718, float phase at L2768, generic phase at L2812 - Python/bytecodes.c L635-L643 and L657-L703:
BINARY_OP_MULTIPLY_INT - Objects/longobject.c L53-L58 (
is_medium_int), L80-L85 (KARATSUBA_CUTOFF), L328-L350 (medium_from_stwodigits), L3934-L3952 (x_mul), L4073-L4123 (k_mul, cutoff test at L4108-L4113, lopsided test at L4122), L4287 (k_lopsided_mul), L4343-L4357 (long_mul) - Include/cpython/longintrepr.h L42-L61 and L64-L100 (digits,
lv_tag), L121-L125 (_PyLong_IsCompact) - Include/internal/pycore_runtime_structs.h L97-L98; at v3.14.6, L109-L110; Include/internal/pycore_long.h L67-L68
- Objects/stringlib/split.h L14-L18 and L53-L93; Objects/unicodeobject.c L10335-L10370
- Python/bltinmodule.c L1571-L1606:
map_next
Documentation:
- What’s New in Python 3.0 (removal of
reduce(),map()returns an iterator) - What’s New in Python 3.8 (
math.prod) - What’s New in Python 3.11 (PEP 659, inlined Python function calls)
- What’s New in Python 3.14 (
reducekeywordinitial, deprecation, new opcodes) - What’s New in Python 3.15 (PEP 661
sentinel) - math.prod, functools.reduce, sys.setprofile
grep -rl /lib/python/reduce-prod-and-ints/
ls python/
- draft Counter, most_common and heapq: top-k in the standard libraryHow collections.Counter counts, how most_common and heapq.nsmallest pick the top few, and why they break ties in opposite directions, read from the CPython 3.15.2 source.
- draft How a Python dict worksInside CPython 3.15's dict: the index table and entries array, the probe sequence, resizing, deletions, and why counting with a dict is linear.
- draft How Python sorts: runs, galloping and powersortWhat CPython 3.15's list.sort does with your data: natural runs, binary insertion sort, a powersort merge stack, galloping, and type-specialised compares.