In Python 3.3, itertools.accumulate()
, which normally repeatedly applies an addition operation to the supplied iterable, can now take a function argument as a parameter; this means it now overlaps with functools.reduce()
. With a cursory look, the main differences between the two now would seem to be:
accumulate()
defaults to summing but doesn't let you supply an extra initial condition explicitly while reduce()
doesn't default to any method but does let you supply an initial condition for use with 1/0-element sequences, andaccumulate()
takes the iterable first while reduce()
takes the function first.Are there any other differences between the two? Or is this just a matter of behavior of two functions with initially distinct uses beginning to converge over time?
itertools is a module in Python that provides functions. These functions help in iterating through iterables. The accumulate() method in the itertools module returns a new iterator. This consists of the sum of the elements' accumulation in the iterable or the results of the binary function.
The reduce() function in python is defined in functools module and doesn't return multiple values or any iterator, it just returns a single value as output which is the result of whole iterable getting reduced to only single integer or string or boolean.
From what I can understand, Python's reduce automatically sets the iterative variable and the accumulator in the function passed to the first two values of the list given in reduce.
It seems that accumulate
keeps the previous results, whereas reduce
(which is known as fold in other languages) does not necessarily.
e.g. list(accumulate([1,2,3], operator.add))
would return [1,3,6]
whereas a plain fold would return 6
Also (just for fun, don't do this) you can define accumulate
in terms of reduce
def accumulate(xs, f): return reduce(lambda a, x: a + [f(a[-1], x)], xs[1:], [xs[0]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With