Intricacies of Python

Vinita
2 min readJul 29, 2020

The Difference Between Reduce() and Accumulate() Function in Python:

Difference between Reduce() and Accumulate()

While we all know the use of these two, still sometimes it becomes doubtful for the beginners to understand the very minute differences and needs of a particular function, and sometimes a mere comma can get you an error :)

So, I thought to share these minute things, if helps someone as new as me.

  1. Reduce() is a part of functools library Whereas Accumulate is a part of itertools library.
  2. Reduce() takes 1st argument as function and 2nd argument as the sequence, Whereas Accumulate() takes 1st argument as a sequence and 2nd argument as a function().
  3. While Reduce() gives just the total of all, or the final result is displayed as One Answer, The Accumulate() function displays the List of the result for every execution between the elements, for example:

if the result is [1,4,8,18,32]

This implies that, 1 is the result of the execution of the given function (x+y) on the first and second element of the given list (lis).

Similarly, 4 is the result of the execution of the function(x+y) on this result and the third element in the list (lis).

Similarly, 8 must be the result of this function (x+y), between 4 and the fourth element.

Similarly, it keeps on displaying result for each execution till the final sum of 32. And because of the this reason, The Accumulate() function uses List Command .

Whereas Reduce() does NOT need to use the List function,

as it displays only the final sum, the final result of the execution on the whole list at Once, i.e. 32.

4. For Example:

While using Accumulate():

print(list(vin.accumulate(lis,lambda x,y:x+y)

=> [1,4,8,18,32]

whereas while using Reduce() function

print (reduce(lambda x,y:x+y, lis))

=> 32

Thanks :)

@Data Folkz

--

--

No responses yet