March 2003
Intermediate to advanced
656 pages
39h 30m
English
reduce
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): ifinitis None:init,seq=seq[0],seq[1:] foriteminseq: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)Read now
Unlock full access