Python Glossary Русский

all Python 3functoolsterm

functools.reduce

folding

Folds an iterable by applying a function cumulatively from left to right. The optional initial is the starting value.

Syntax

functools.reduce(function, iterable, /[, initial])

With no initial, reduce raises TypeError on an empty iterable and, on a one-element one, returns that element without ever calling the function — pass a starting value explicitly unless you really want that behaviour. Python 3 moved reduce out of the builtins on purpose: a plain loop or sum(), math.prod(), str.join() usually reads better, and folding lists or strings this way is quadratic.

Examples

from functools import reduce
result = reduce(lambda a, b: a + b, [1,2,3,4,5])
print(result)  # → 15
product = reduce(lambda a, b: a * b, [1,2,3,4,5])
print(product)  # → 120
maximum = reduce(lambda a, b: a if a > b else b, [3,1,4,1,5,9])
print(maximum)  # → 9
words = ['Hello', ' ', 'World']
sentence = reduce(lambda a, b: a + b, words)
print(sentence)  # → Hello World
from functools import reduce
# С начальным значением
total = reduce(lambda a, b: a + b, [1,2,3], 100)
print(total)  # → 106
from functools import reduce
# Подсчёт вхождений
from collections import Counter
nums = [1,1,2,3,1]
result2 = reduce(lambda acc, x: acc + (1 if x==1 else 0), nums, 0)
print(result2)  # → 3

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy