brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's itertools.pairwise walks a list in overlapping pairs

Python
~/tips/tip-python-itertools-pairwise

from itertools import pairwise

Gives each item of a list together with the next one, handy for differences and gaps.

Comparing each item with the next one is a classic loop with an index and a [i + 1] that goes out of range if you are not careful. Python 3.10 added a function for exactly this.

from itertools import pairwise

list(pairwise('ABCDEFG'))
# [('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G')]

You get successive overlapping pairs. The result has one item fewer than the input, and it is empty when there are fewer than two values, so no index errors.

A practical example: the time between log entries, to find gaps.

from itertools import pairwise

stamps = [1000, 1060, 1120, 1900, 1960]
for a, b in pairwise(stamps):
    if b - a > 300:
        print(f"gap of {b - a} seconds after {a}")

Or the change in disk usage per day from a list of daily readings. Anything where “this one compared to the previous one” is the question.

It works on any iterable, not only lists, so you can feed it lines from a file or a generator without loading everything in memory first.

Caveat: it is Python 3.10 and newer. On an older server Python you get an ImportError, so check python3 --version on the machine where the script runs, not just on your laptop. The docs also show how the function works if you need a version for older Pythons.

Further reading: Python docs: itertools.pairwise

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link