Sub topic 7
Running totals with accumulate and starmap
This chapter assumes you know Python functions, lambda expressions, and the basics of iterators from earlier chapters. Both tools here are lazy. They produce one result at a time and keep almost nothing in memory.
Running results with accumulate
accumulate(iterable, func=None, *, initial=None) yields the result of combining items one at a time. By default it adds. Each output is the previous output combined with the next input item.
from itertools import accumulate
print(list(accumulate([1, 2, 3, 4])))
print(list(accumulate([3, 1, 4, 1, 5], max)))The first call prints [1, 3, 6, 10], which are running sums. The second passes max as the function and prints [3, 3, 4, 4, 5], the largest value seen so far.
The first output is always the first input item, unchanged. The function runs only from the second item on.
Any two-argument function works
The function takes two arguments: the running result and the next item. You can use a lambda or a function from operator.
from itertools import accumulate
from operator import mul
print(list(accumulate(range(1, 6), mul)))This prints [1, 2, 6, 24, 120], the running factorials.
Starting from a value with initial
Use initial to begin from a chosen value. That value becomes the first output, so the result has one more item than the input.
from itertools import accumulate
balance = accumulate([50, -20, 30], initial=100)
print(list(balance))This prints [100, 150, 130, 160]. The starting balance appears first, followed by the balance after each transaction.
Applying a function to argument tuples with starmap
starmap(func, iterable) is like map, except each item is a tuple that gets unpacked into the function's arguments. Use it when your data is already grouped in tuples.
from itertools import starmap
from operator import pow
pairs = [(2, 5), (3, 2), (10, 3)]
print(list(starmap(pow, pairs)))This prints [32, 9, 1000]. The call starmap(pow, pairs) runs pow(2, 5), pow(3, 2) and pow(10, 3).
starmap(f, rows) behaves like (f(*row) for row in rows). Compare it with map, which would need the function to accept a single tuple.
| Tool | Item `(2, 5)` becomes the call |
|---|---|
| `map(f, rows)` | `f((2, 5))` |
| `starmap(f, rows)` | `f(2, 5)` |
| `map(f, xs, ys)` | `f(x, y)` taken from two separate iterables |
map with two iterables does the same job when the values sit in two separate sequences. starmap is the better fit when they arrive as tuples, for example rows from zip or from a file.
Combining the two
Compound growth is a running result, and accumulate handles it with a two-argument lambda.
from itertools import accumulate, starmap
rates = [0.05, 0.02, 0.03]
value = accumulate(rates, lambda total, r: total * (1 + r), initial=1000)
print([round(v, 2) for v in value])
lines = [("apple", 3, 0.5), ("pear", 2, 0.75)]
costs = starmap(lambda name, qty, price: (name, qty * price), lines)
print(list(costs))The first print shows [1000, 1050.0, 1071.0, 1103.13]. The second shows [('apple', 1.5), ('pear', 1.5)].
Common mistakes
- Expecting a final value only.
accumulateyields every intermediate result. To get just the last one, usefunctools.reduce, or consume the iterator and keep the last item. - Forgetting the output length with
initial. The result has one extra item. Code that zips outputs with inputs can end up off by one. - Passing tuples to
map. A function with two parameters fails with aTypeErrorwhenmaphands it one tuple. Usestarmap. - Reusing the result. Both return iterators. After one full pass they are empty, so wrap the result in
listif you need a second pass.
Exercise
Given deposits = [10, 20, 30], write one expression with accumulate that gives the running totals starting from an opening balance of 5. What list does it produce?
Show answer
list(accumulate(deposits, initial=5)) produces [5, 15, 35, 65]. The opening balance comes first, so the output has four items for three inputs.
Exercise
You have points = [(0, 1), (2, 3), (4, 5)] and want the sum of each pair as a list. Which tool do you use, and what is the code?
Show answer
Use starmap with operator.add: list(starmap(add, points)), after from operator import add. It gives [1, 5, 9].