Python itertools.pairwise() Function

Python Programming Tutorials


Python's itertools.pairwise() gives you each item beside the item that follows it. That small pattern is useful whenever order matters: compare consecutive readings, calculate changes between prices, or inspect each step in a route. You can write the loop yourself, but pairwise() makes the intent clear and works with any iterable.

The function joined the standard library in Python 3.10. It returns an iterator, so it produces pairs as you consume them instead of first building a second list.

How Python pairwise() works

Import pairwise from itertools and pass it one iterable. Its first result contains items 1 and 2; the next contains items 2 and 3. Pairs therefore overlap by one item. With four input values you get three pairs. An empty iterable or a single item produces no pairs.

Example: Compare consecutive readings

from itertools import pairwise

# Compare each reading with the one immediately before it.
readings = [18, 21, 19, 24]
for previous, current in pairwise(readings):
    change = current - previous
    print(f"{previous} -> {current}: {change:+d}")

# A one-item input has no adjacent pair.
print(list(pairwise([7])))

The output is:

18 -> 21: +3
21 -> 19: -2
19 -> 24: +5
[]

Each loop iteration receives a two-item tuple. Destructuring it as previous, current lets you name the values by their role. The final [] confirms that a one-item input has no neighbor to pair with.

Use pairwise() with strings and other iterables

The input need not be a list. A string supplies consecutive characters, while a generator can supply values one at a time. The function does not sort, remove duplicates, or wrap the last item back to the first. It follows the input order exactly.

Example: Find repeated neighboring letters

from itertools import pairwise

word = "committee"
# Report only repeated letters that touch each other.
for left, right in pairwise(word):
    if left == right:
        print(left + right)

This prints mm, tt, and ee. If you need both characters and their positions, use enumerate(pairwise(word)); each index identifies the first character in that pair.

Calculate changes without indexing

A common alternative is to loop over numeric indexes and access values[index - 1] and values[index]. That is fine when you also need random access, but pairwise is usually easier to read for a simple adjacent comparison. It also accepts iterables that have no numeric index.

Example: Track price changes

from itertools import pairwise

prices = [120, 125, 123, 130]
changes = [current - previous for previous, current in pairwise(prices)]
print(changes)  # [5, -2, 7]

The comprehension creates a list because we ask it to. pairwise(prices) itself remains an iterator. If you only need to inspect each change once, a regular for loop avoids storing that extra list.

Handle short and one-use inputs

Do not assume the function always yields a pair. For zero or one input item, it yields nothing. This makes ordinary loops safe, but a calculation such as max(changes) needs an empty-input plan. For example, you might use max(changes, default=0) when zero is a meaningful fallback.

An iterator can be consumed only once. If you store pairs = pairwise(values) and convert it to a list, a second conversion of the same pairs returns an empty list. Call pairwise(values) again if values is reusable, or save the pairs when you truly need multiple passes.

Tip: For non-overlapping groups of two, use itertools.batched(iterable, 2) in Python 3.12 or newer. Pairwise is specifically for overlapping neighbors.

When should you use pairwise()?

Choose pairwise when the relationship between neighboring items is the point of the code. Good uses include detecting a sudden change, checking that timestamps increase, measuring distance between successive points, and finding adjacent duplicates. If your algorithm needs windows of three or more items, pairwise alone is not the right shape.

Conclusion

itertools.pairwise() turns an ordered iterable into overlapping two-item tuples. Import it, loop through the pairs, and give each value a clear name. Once you understand that a sequence of n items yields n − 1 pairs, you can use it to express adjacent comparisons with less indexing and fewer edge-case mistakes.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram