Home

functoolsreduce

functools.reduce is a function in the Python standard library that applies a binary function cumulatively to the items of an iterable, from left to right, to produce a single value. It is defined in the functools module; in Python 2 it was a built-in function, but in Python 3 it resides in functools and is imported with from functools import reduce.

Signature and behavior: reduce(function, iterable [, initializer]). The function is called with two arguments: the accumulated value

Examples: reduce(lambda a, b: a + b, [1, 2, 3, 4]) returns 10. reduce(lambda a, b: a * b,

Notes: reduce implements a left fold, applying the function from the first element (or the initializer) toward

and
the
next
item.
If
an
initializer
is
provided,
it
is
placed
before
the
first
item
and
the
reduction
starts
with
that
value.
If
no
initializer
is
given,
the
first
item
of
the
iterable
serves
as
the
initial
value.
If
the
iterable
is
empty
and
no
initializer
is
provided,
reduce
raises
TypeError:
reduce()
of
empty
sequence
with
no
initial
value.
If
an
initializer
is
provided
and
the
iterable
is
empty,
the
initializer
is
returned.
[1,
2,
3,
4],
1)
returns
24.
Using
an
operator:
from
operator
import
add;
reduce(add,
[1,
2,
3,
4])
also
yields
10.
the
end.
It
accepts
any
callable
that
takes
two
arguments.
For
simple
numeric
sums,
sum
is
often
preferred.
Other
patterns
include
using
reduce
with
complex
merging
logic
or
combining
elements
into
a
single
structure.