On this page
functools.reduce
Prev: functools.partialmethod | Up: functools | Next: functools.singledispatch
Rel: functools.cache, functools.cached_property, functools.cmp_to_key, functools.lru_cache
Ref: docs.python.org — functools.reduce
Tags: #public #python3 #stdlib #functools
Import
import functools
from functools import reduce
Signature & Overview
functools.reduce(...)
Apply a function of two arguments cumulatively to the items of an iterable, from left to right.
Usage
from functools import reduce
import operator
assert reduce(operator.mul, [2, 3, 4], 1) == 24
assert reduce(lambda acc, d: acc | d, [{"a": 1}, {"b": 2}], {}) == {"a": 1, "b": 2}
Gotchas
- Empty iterable without
initialraisesTypeError: Always pass an explicitinitialvalue when the input might be empty. - Prefer built-ins when available: Use
sum(),math.prod(),any(),all(),min(),max(), or a plainforloop when clearer thanreduce().
REPL Inspect
from functools import reduce
help(reduce)
Linked from
Related notes
- tuts/python3/stdlib_module/functools/partialmethod Linked here; links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/singledispatch Linked here; links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/functools/cache Linked here; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/cached_property Linked here; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/cmp_to_key Linked here; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/lru_cache Linked here; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/partial shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/singledispatchmethod shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/total_ordering shared tags: #functools, #stdlib