Back to the blog

Tony CantaveSummarizing Records in Python with itertools: chain, groupby, islice and accumulate

By Tony Cantave ·

A lot of the small Python scripts I write, both for AI evaluation work and for my own projects, end with the same question: what are the totals? Totals by town, by day, by category, plus a running number so I can see where the week went. You can do all of that with plain loops and dictionaries, but the itertools module in the standard library has four tools that make this kind of code shorter and easier to check: chain, groupby, islice and accumulate. Here is how I use each one, and the two groupby mistakes that catch almost everyone the first time.

The sample data

from itertools import accumulate, chain, groupby, islice
from operator import itemgetter

week_one = [
    {"day": "Mon", "town": "New Haven", "amount": 120},
    {"day": "Mon", "town": "Hamden", "amount": 45},
    {"day": "Tue", "town": "New Haven", "amount": 80},
]
week_two = [
    {"day": "Mon", "town": "Bridgeport", "amount": 60},
    {"day": "Wed", "town": "New Haven", "amount": 95},
    {"day": "Wed", "town": "Hamden", "amount": 30},
]

Two small exports that need to be treated as one list. That is the first job.

chain: treat several lists as one

rows = list(chain(week_one, week_two))
print(len(rows))  # 6

chain walks through the first iterable, then the second, without building a combined copy until you ask for one. If you have a list of lists, for example one list per file, use chain.from_iterable:

all_weeks = [week_one, week_two]
rows = list(chain.from_iterable(all_weeks))

I like this better than week_one + week_two because it works the same way for generators, file readers and anything else that is not a list.

groupby: totals per key, after sorting

This is the tool people reach for first and get wrong first. groupby only groups items that are next to each other. It does not look across the whole list. Watch what happens on unsorted data:

towns = [town for town, _ in groupby(rows, key=itemgetter("town"))]
print(towns)
# ['New Haven', 'Hamden', 'New Haven', 'Bridgeport', 'New Haven', 'Hamden']

Six groups instead of three. No error, just wrong totals. The fix is to sort by the same key first:

by_town = sorted(rows, key=itemgetter("town"))

totals = {
    town: sum(row["amount"] for row in group)
    for town, group in groupby(by_town, key=itemgetter("town"))
}
print(totals)
# {'Bridgeport': 60, 'Hamden': 75, 'New Haven': 295}

My rule: the key in sorted and the key in groupby should be the exact same expression. Using itemgetter("town") in both places makes that easy to see in a review.

The second groupby mistake: groups are used up

Each group that groupby gives you is a one pass iterator tied to the main one. Once groupby moves to the next key, the previous group is gone. This looks reasonable and quietly fails:

groups = list(groupby(by_town, key=itemgetter("town")))
print(list(groups[0][1]))  # []

The list call advanced through every group, so the saved group iterators are empty. If you need the rows again later, turn each group into a list while you are on it:

rows_by_town = {
    town: list(group)
    for town, group in groupby(by_town, key=itemgetter("town"))
}
print(len(rows_by_town["New Haven"]))  # 3

If you only need totals and never the rows, collections.Counter or defaultdict can skip the sorting step entirely. I use groupby when the data is already sorted, such as a log ordered by date, or when I want to process one group at a time without holding everything in memory.

islice: look at the first few rows of a big file

Before I write any summary code, I look at the real data. With a large CSV, islice lets me preview the first rows without reading the whole file:

import csv

with open("sales.csv", newline="") as f:
    for row in islice(csv.DictReader(f), 5):
        print(row)

islice works on any iterator, so it is also handy for testing a generator pipeline on a small slice before running it on everything.

accumulate: running totals

amounts = [row["amount"] for row in rows]
running = list(accumulate(amounts))
print(running)
# [120, 165, 245, 305, 400, 430]

accumulate adds as it goes. It also takes a function, so accumulate(amounts, max) gives a running high, and the initial argument (Python 3.8 and later) lets you start from a carried over balance.

Check the numbers before trusting them

Every summary gets one or two asserts. The cheapest check is that the parts add up to the whole:

assert sum(amounts) == sum(totals.values()) == 430
assert max(running) == 430
assert len(totals) == 3

If the unsorted groupby bug had slipped in, the dictionary would still sum correctly but the per town values would be wrong, which is why I also compare one total by hand, like New Haven at 120 plus 80 plus 95.

Why this matters to me

I spent years running production and logistics operations before moving into software, and a daily total that is wrong in a way nobody notices is the most expensive kind of wrong. The same is true in code. chain, groupby, islice and accumulate are small tools, but used with a sort, a preview and a couple of asserts, they turn a pile of rows into numbers you can stand behind.