11 posts
This article helps to give an introduction of reduce fuunction and accumulate function.Both the functions are used to process the input_list as a sequential pairs.
I am going to explain the differences with the help of an example.
import functools
list = [1, 2, 3, 4, 5]
retVal = functools.reduce(lambda x, y: x+y, list)
print(retVal)
Result: 15
import itertools
list = [1, 2, 3, 4, 5]
retList = list(itertools.accumulate(list, lambda x, y: x+y))
print(retList)
Result: [1, 3, 6, 10, 15]
Procedure: When you feed an input list to the processing function of reduce, first it tries to take the first two elements process it, the result is proceded to the next element then at that time the pair is the sum calculated in the previous step and the next element. So this continues until unless the list empty. As a final output it gives only one element.Unlike reduce accumulate stores every result and returns as a lilst.
Please log in to leave a comment.