Home » Programming » Python » Python Accumulate

Using the Python ‘accumulate()’ Function to Aggregate Data, With Examples

This article will detail how to use the ‘accumulate()’ function in Python and provide some easy-to-follow example code.

The accumulate() function in Python will process an iterable (iterables are things like lists, dictionaries, sets, or tuples – collections containing items which can be looped over) – returning the accumulated sum of the value of each item or running a given function on each item. The value of the accumulated value is stored for each step and returned with the result.

The syntax and code in this article are written for Python 3.

Syntax for Python accumulate()

itertools.accumulate(ITERABLE[, FUNCTION, INITIALIZER])

Note that:

  • FUNCTION is a standard Python function, previously defined in your code
    • It should accept two parameters
      • The first parameter is the current accumulated value up until this point while processing items in the lists.
      • The second parameter is used to read each item in the iterable passed to the filter() function.
    • This function’s return value should be the will be passed to the next iteration as the first parameter.
      • This is the new accumulated value, passed to the next iteration so that the next item in the list can be added to it (or subtracted from it, or whatever it is you want to do)
  • ITERABLE should be a variable or value containing an iterable
    • Lists, dictionaries, sets, and tuples are common iterables
  • INITIALIZER is the initial accumulated value before any items have been processed or the default value of the return value
    • It is optional
    • If it is present, it will be the first value in the list of results returned by accumulate() – making the results list one entry longer than the supplied ITERABLE
  • accumulate() will return an iterator (an object containing some values) containing the accumulated value after each item in ITERABLE has been processed
    • The last value in the returned result will be the final result, the final accumulated value
    • This is probably easier seen in action – see the first example below

Example Usage of accumulate() to Calculate the Sum

This example will sum up a list of numbers using accumulate():

# accumulate() is part of the itertools library, which must be imported
import itertools

# Define a list of the number of carrots picked across several days
carrotsPickedToday = [3, 5, 0, 6, 0, 1]

# Calculate the sum of the numbers in carrotsPickedToday using accumulate()
# Notice that only carrotsPickedToday has been passed to accumulate() - as the function is optional, it will default to summing the values in the supplied list
result = itertools.accumulate(carrotsPickedToday)

# Print the result - it will be a list!
for item in result:
    print(item)

This code will output:

3
8
8
14
14
15

Why is the result a list? Each entry is the current accumulated value, showing each step until the final accumulated value is reached at the end of the list. As there is no initial accumulator value, the result of the first iteration is simply 3 as there was nothing to add to it yet.

Example Usage of accumulate() with Other Calculations

This example will show you how to use a custom function to calculate the accumulated value:

# accumulate() is part of the itertools library, which must be imported
import itertools

# Define a list containing some numbers
someNumbers = [4, 6, 8, 2, 5]

# Define a function which doubles the given numbers, and adds it to the current accumulation
def doubleAndSum(accumulated, item):
    return (item * 2 ) + accumulated

# Apply the doubleAndSum function to each item in someNumbers using accumulate()
result = itertools.accumulate(someNumbers, doubleAndSum)

# Print the result - it will be a list!
for item in result:
    print(item)

This will output:

4
16
32
36
46

Again, the returned value from accumulate is a list containing the value of the accumulated value after each item has been processed – the final value being last. Again, the first value is unchanged as there is not yet any accumulated value to use in the calculation for that iteration.

Similar Python Functions

Several other Python Functions work similarly to map() but may suit your scenario better – give them a look:

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment