Sub topic 7
Running totals with accumulate and starmap
This chapter covers two functions from itertools that apply a function to a stream as it flows past. accumulate carries a value forward from one item to the next. starmap unpacks each item into the arguments of a call.
You should already know how iterators are consumed once (see the earlier chapter on the iteration protocol) and be comfortable with lambda and the operator module. Both functions are lazy. They return iterators and compute a value only when you ask for it.
What accumulate does
accumulate(iterable, func=None, *, initial=None) yields a running result. With no function, it adds. The first output is the first input, unchanged. Every later output is func(previous_output, next_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]. The second prints [3, 3, 4, 4, 5], a running maximum.
The output has the same length as the input. This is the main difference from functools.reduce, which returns only the final value. If you want just the last total, use reduce or sum. If you want every intermediate state, use accumulate.
The function signature
The function you pass takes two arguments: the accumulated value, then the new item. Any two-argument callable works, including the ones in operator.
from itertools import accumulate
from operator import mul
print(list(accumulate(range(1, 6), mul)))
print(list(accumulate(["a", "b", "c"])))The first line prints [1, 2, 6, 24, 120], the factorials of 1 to 5. The second prints ['a', 'ab', 'abc'], because the default operation is + and it works on strings.
The accumulated value does not need to have the same type as the items. Here the accumulator is a tuple and the items are ignored:
from itertools import accumulate, repeat
steps = accumulate(repeat(None, 8), lambda pair, _: (pair[1], pair[0] + pair[1]), initial=(0, 1))
print([a for a, _ in steps])This prints [0, 1, 1, 2, 3, 5, 8, 13, 21]. The repeat(None, 8) stream only controls how many steps happen. Because initial=(0, 1) is given, the output has nine values: the initial one plus eight steps.
The initial argument
Since Python 3.8, initial puts a starting value in front of the stream. It is emitted first, so the output has one more element than the input.
from itertools import accumulate
deposits = [100, -30, 50, -80]
print(list(accumulate(deposits)))
print(list(accumulate(deposits, initial=500)))The output is:
[100, 70, 120, 40]
[500, 600, 570, 620, 540]Use initial for two reasons:
- You have a real starting state, such as an opening balance.
- You want an output for the "before anything happened" step. This is common when plotting or when comparing neighbouring totals.
An empty input gives an empty output. With initial, an empty input yields just the initial value.
from itertools import accumulate
print(list(accumulate([])))
print(list(accumulate([], initial=0)))This prints [] and then [0].
A practical use: finding the first threshold crossing
Because accumulate is lazy, you can stop as soon as a condition is met. The rest of the input is never read.
from itertools import accumulate
deposits = [100, -30, -90, 50]
balances = accumulate(deposits, initial=50)
first_overdraft = next((i for i, b in enumerate(balances) if b < 0), None)
print(first_overdraft)The balances are 50, 150, 120, 30, 80, so none is negative and the code prints None. Change the initial value to 0 and the balances become 0, 100, 70, -20, 30, so the code prints 3. The default None in next prevents a StopIteration when nothing matches.
What starmap does
starmap(func, iterable) calls func(*item) for each item. It exists for the case where each item is already a tuple of arguments.
from itertools import starmap
pairs = [(2, 3), (3, 2), (10, 3)]
print(list(starmap(pow, pairs)))This prints [8, 9, 1000].
Compare it with map. map takes one iterable per argument, while starmap takes one iterable of argument tuples:
from itertools import starmap
bases = [2, 3, 10]
exponents = [3, 2, 3]
print(list(map(pow, bases, exponents)))
print(list(starmap(pow, zip(bases, exponents))))Both lines print [8, 9, 1000]. The two forms are equivalent when the data starts as separate sequences. starmap is the better fit when your data is already a stream of tuples, such as database rows or the output of zip, enumerate or product.
| Tool | Input shape | Output length | Calls function as |
|---|---|---|---|
| `map(f, a, b)` | one iterable per argument | shortest input | `f(a_i, b_i)` |
| `starmap(f, rows)` | one iterable of tuples | same as input | `f(*row)` |
| `accumulate(xs, f)` | one iterable | same as input | `f(total, x)` |
| `functools.reduce(f, xs)` | one iterable | single value | `f(total, x)` |
Combining the two
The two functions combine well. A running average needs the running total and the count of items so far. accumulate supplies the first, count supplies the second, and starmap divides them.
from itertools import accumulate, count, starmap
from operator import truediv
values = [10, 20, 30, 40]
averages = starmap(truediv, zip(accumulate(values), count(1)))
print(list(averages))This prints [10.0, 15.0, 20.0, 25.0]. zip stops at the shortest input, so the infinite count(1) is safe here. Nothing is stored beyond the current total.
This works on a stream of any length, including a generator that reads a large file line by line.
Common errors
Reusing a consumed result
Both functions return iterators. Once you have run list() on one, a second pass gives an empty result.
from itertools import accumulate
running = accumulate([1, 2, 3])
print(list(running))
print(list(running))The output is [1, 3, 6] and then []. Store the list if you need it twice, or build a new accumulate call.
Swapping the function arguments
The accumulated value always comes first. A function like subtraction is not symmetric, so the order matters:
from itertools import accumulate
from operator import sub
print(list(accumulate([10, 1, 2, 3], sub)))This prints [10, 9, 7, 4], which is 10, 10-1, 9-2 and 7-3. If you wrote lambda x, total: ... by mistake, you would get different values and no error.
Passing non-tuples to starmap
starmap unpacks each item with *. If an item is not an iterable of arguments, such as a bare integer, you get a TypeError. A string is iterable, so starmap(f, ["ab"]) calls f("a", "b"), which is rarely what you want. Check that each item has the right number of elements for the function.
Forgetting that the first output is not transformed
With a custom function, the first item passes through unchanged. If your function converts values, for example turning strings into numbers, the first output will still be the raw item. Convert before accumulating, or use initial:
from itertools import accumulate
words = ["1", "2", "3"]
print(list(accumulate(map(int, words))))This prints [1, 3, 6]. Applying int first with map keeps the types consistent.
Using accumulate for the wrong job
Floating-point sums accumulate rounding error, and accumulate does not compensate for it. For one precise total, math.fsum is more accurate. For exact decimal money, pass Decimal values. Also, if you only need the final result, sum or reduce avoids producing outputs you will discard.
Summary of when to choose each
- Use
accumulatewhen you need every intermediate state: running sums, running maxima, balances, cumulative products. - Use
starmapwhen items are already argument tuples and a function should be applied to each. - Pair them when a result depends on both a running value and a position, as in the running average.
Exercise
Given prices = [4, 8, 15, 16, 23, 42], write code that prints the running minimum of the list as a list, and then prints the index of the first position where the running sum exceeds 40.
Show answer
Use accumulate with min for the first part and accumulate with enumerate and next for the second. from itertools import accumulate prices = [4, 8, 15, 16, 23, 42] print(list(accumulate(prices, min))) totals = accumulate(prices) print(next(i for i, t in enumerate(totals) if t > 40)) The running minimum is [4, 4, 4, 4, 4, 4]. The running sums are 4, 12, 27, 43, ..., so the first sum above 40 is at index 3, and the code prints 3.
Exercise
You have rows = [(1, 2, 3), (4, 5, 6)]. Use starmap to produce the sum of each row without writing a loop. Why does starmap(sum, rows) fail?
Show answer
sum takes one iterable, not three separate arguments, so use a wrapper: list(starmap(lambda a, b, c: a + b + c, rows)) gives [6, 15]. The call starmap(sum, rows) runs sum(1, 2, 3), which raises a TypeError because starmap unpacks each tuple into separate arguments and sum accepts only one iterable (plus an optional start value). The simpler fix is map(sum, rows), which passes each tuple as one argument and gives [6, 15].