Name
reduce
Synopsis
reduce(func
,seq
[,init
])
Applies funct
to the items of
seq
, from left to right, to reduce the
sequence to a single value. func
must be
callable with two arguments. reduce
calls
func
on the first two items of
seq
, then on the result of the first call
and the third item, and so on. reduce
returns the
result of the last such call. When init
is
present, it is used before
seq
’s first item, if any.
When init
is missing,
seq
must be non-empty. When
init
is missing and
seq
has only one item,
reduce
returns
seq
[0]
. Similarly, when
init
is present and
seq
is empty, reduce
returns init
. The built-in
reduce
is equivalent to:
def reduce_equivalent(func
,seq
,init
=None): ifinit
is None:init
,seq
=seq
[0],seq
[1:] foritem
inseq
:init
=func
(init
,item
) returninit
A typical use of reduce
is to compute the sum of a
sequence of numbers:
thesum = reduce(operator.add, seq
, 0)
Get Python in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.