CKTIS / Python
functools.reduce
Combines each item with a running accumulator from left to right.
Version: Python 3.14; repository image, production runtime not attested
Syntax
functools.reduce(function, iterable, /)
functools.reduce(function, iterable, /, initial)Combines each item with a running accumulator from left to right.
Providing an initial accumulator makes the result defined on empty input. Changing association can change results for subtraction.
Fold from the left, calling function(accumulator, next_item) and retaining only the final value. Without initial the first item seeds the fold; a singleton is returned unchanged and empty input raises TypeError. Python 3.14 accepts initial by keyword. The example evaluates (10-3)-2 to 5; for an empty input it returns its initial 10.
from functools import reduce
from operator import sub
assert reduce(sub, [3, 2], initial=10) == 5
assert reduce(sub, [7]) == 7 and reduce(sub, [], initial=10) == 10
try:
reduce(sub, [])
except TypeError:
pass
else:
raise AssertionError
Examples
import functools
from operator import sub
print(functools.reduce(sub, [3, 2], 10))
print(functools.reduce(sub, [], 10))
Result
5 10
Fold from the left, calling function(accumulator, next_item) and retaining only the final value. Without initial the first item seeds the fold; a singleton is returned unchanged and empty input raises TypeError. Python 3.14 accepts initial by keyword. The example evaluates (10-3)-2 to 5; for an empty input it returns its initial 10.