The accumulate()
function in itertools
module takes a function and an iterable as arguments and returns a series of accumulated results.
When the function is called without a function argument as in the above case, it simply calculates the cumulative sums of the elements of the given iterable object. It returns an iterator object of the accumulated sums.
accumulate(iterable, func = None, initial = 0)
copy
iterable |
Required. This is the iterable object(e.g list, tuple, set, range, etc ) whose elements are to be accumulated over. |
func |
Optional. Specifies a binary function(takes two arguments) to be used for the accumulation. If not given the successive sums of the values of the elements will be returned. |
initial |
Optional. Specifies the initial value of the accumulated result. By default, the initial value is set to 0. |
The function returns an iterator which successively applies the given function to the iterable elements.
In the above example, we used the accumulate()
function to find the cumulative product of integers from 1 to 9. We specified the initial
value as 1 because if we hadn't, the default value( 0) would have been used meaning that all the results would have yielded zero.
How the function works
In the first call , the accumulate iterator calls the given function with the initial value and the first item in the iterable object. In the second call the function will be called with calculated result of the first call and the second item in the list. The calculated result is then saved and used in the third call and so on. This process continues until all the items in the iterable object have been passed to the given function.
The following example demonstrated clearly how the function works.
Casting the iterator into an iterable
We can create an iterable object such as a list or a tuple from the accumulated values in the iterator. This can be achieved by calling the constructor of the target iterable type with the iterator object.