r/pythontips • • 23h ago

Standard_Lib Tip: use itertools.pairwise instead of zip(a, a[1:]) to loop over consecutive pairs

17 Upvotes

If you need to compare each item with the next one, you may have written this:

temps = [20, 22, 21, 25, 24]
changes = [b - a for a, b in zip(temps, temps[1:])]
print(changes)   # [2, -1, 4, -1]

Since Python 3.10 there’s a function made for it:

from itertools import pairwise

temps = [20, 22, 21, 25, 24]
changes = [b - a for a, b in pairwise(temps)]
print(changes)   # [2, -1, 4, -1]

Same result, and the intent is clearer: “each item with its neighbor”.

Where it’s better than slicing: pairwise works on any iterable, not only on lists. Slicing fails on a generator:

squares = (x * x for x in range(5))
list(pairwise(squares))
# [(0, 1), (1, 4), (4, 9), (9, 16)]

squares = (x * x for x in range(5))
list(zip(squares, squares[1:]))
# TypeError: 'generator' object is not subscriptable

It also doesn’t make a copy of the data the way temps[1:] does, so it’s friendlier for large inputs. (It still pulls items one at a time and remembers just the previous one.)

Edge cases: fewer than two items gives an empty result, with no error:

list(pairwise([1]))    # []
list(pairwise([]))     # []
list(pairwise("abcd")) # [('a', 'b'), ('b', 'c'), ('c', 'd')]

Compatibility: pairwise doesn’t exist before Python 3.10, so on older versions keep the zip(a, a[1:]) form (for sequences) or use the “pairwise” recipe from the itertools documentation.


r/pythontips • • 2h ago

Long_video Giving back to the community - The Complete Backend Development Course (last round)

1 Upvotes

Hey everyone, I decided to make my course free in order to help people.
This course is my backend development course which is about SQL, Python, APIs, Docker, Kubernetes, Linux, Git & More

The link is: https://www.youtube.com/watch?v=CBIu6hcyStg

If you can like and subscribe (and maybe add a comment) I would appreciate it a lot, Thanks.