reduce Folds Left With An Initializer

functools.reduce folds a binary function left to right; without an initializer empty sequences raise TypeError, with one the initial value is returned.

PythonData Integrity

Code

pythonsnippet
22 lines
import functools
import operator

# reduce 把二元函数从左到右折叠进一个累加值
total = functools.reduce(operator.add, [1, 2, 3, 4, 5])
print('sum fold   :', total)

# 无初值时空序列直接抛 TypeError:必须给 initializer 兜底
try:
    functools.reduce(operator.add, [])
except TypeError as exc:
    print('empty      :', exc)

# 有初值时空序列返回初值本身
print('empty init :', functools.reduce(operator.add, [], 0))

# 用 lambda 折叠成结构:逐个把元素追加进累积列表
squares = functools.reduce(lambda acc, n: acc + [n * n], range(1, 6), [])
print('squares    :', squares)

# 连乘用 operator.mul:同样的左折叠
print('product    :', functools.reduce(operator.mul, [2, 3, 4]))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

sum fold   : 15
empty      : reduce() of empty iterable with no initial value
empty init : 0
squares    : [1, 4, 9, 16, 25]
product    : 24

How it works

Module-level bindings hold the data — total, squares — with no function scope in between.

What to watch for

  • Dependency check: operator — not built-in, must be present in the project.

Using it

The demo output is labeled (sum fold :, empty :, empty init :), so every printed line maps back to its originating operation.

Key statements

except TypeError as exc:
    print('empty      :', exc)

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `total`, `squares`.