Python itertools.pairwise: Syntax and Use Cases
A practical guide to Python's itertools.pairwise: syntax, lazy evaluation, examples, edge cases, and comparisons with zip.

itertools.pairwise, added in Python 3.10, returns successive overlapping pairs from any iterable. For an input like [1, 2, 3, 4], it yields (1, 2), (2, 3), and (3, 4) without building an intermediate list. It is useful whenever you need to compare adjacent elements in a sequence.
The Syntax and Return Type
itertools.pairwise takes a single iterable and returns an iterator of tuples. Each tuple contains two consecutive elements from the input. Because the returned object is an iterator, it evaluates the input lazily instead of constructing all pairs up front.
from itertools import pairwise
result = pairwise([1, 2, 3, 4])
print(list(result))
# [(1, 2), (2, 3), (3, 4)]The returned iterator can be consumed only once. If you need to reuse the pairs, convert them to a list first.
Basic Usage Examples
A common use is to compare each element with its predecessor. For instance, you might want to detect where a list changes value or where a difference exceeds a threshold.
from itertools import pairwise
def has_duplicate_adjacent(items):
return any(a == b for a, b in pairwise(items))
print(has_duplicate_adjacent([1, 2, 2, 3])) # True
print(has_duplicate_adjacent([1, 2, 3, 4])) # FalseAnother typical pattern is computing the difference between consecutive measurements:
from itertools import pairwise
readings = [10, 12, 9, 15]
deltas = [b - a for a, b in pairwise(readings)]
print(deltas) # [2, -3, 6]Because pairwise yields tuples, you can unpack them directly in a loop or comprehension.
How pairwise Handles Short Iterables
If the input has fewer than two elements, pairwise yields nothing. This is consistent with the mathematical definition: you cannot form a pair from a single item.
from itertools import pairwise
print(list(pairwise([]))) # []
print(list(pairwise([42]))) # []This behavior is often convenient because it avoids special-case checks. In many algorithms an empty result is the correct outcome; if you do need to detect the no-pairs case, convert the iterator to a list or consume it explicitly.
Memory and Lazy Evaluation
The object returned by pairwise is a lazy iterator. It does not create a list of all pairs up front. Instead, it reads one element at a time and keeps only the previous element in memory. This makes it suitable for large or infinite iterables, as long as you do not convert the entire result to a list.
from itertools import pairwise, islice
# Works with an infinite sequence
pairs = pairwise(range(10**9))
first_three = list(islice(pairs, 3))
print(first_three) # [(0, 1), (1, 2), (2, 3)]The memory footprint is O(1) beyond the input iterator itself. This is a clear advantage over approaches that create a sliced copy of the input, such as zip(items, items[1:]), which duplicates the list.
Comparing pairwise with zip
Before Python 3.10, a common way to get successive pairs was to use zip with a sliced list:
items = [1, 2, 3, 4]
pairs = zip(items, items[1:])This works but has a hidden cost: items[1:] creates a new list containing all elements except the first. For large lists, that is an unnecessary allocation. pairwise avoids this by reading directly from the original iterator.
There is also a subtle difference when the input is an iterator rather than a list. With zip(items, items[1:]), the slicing operation fails because iterators do not support indexing. pairwise works with any iterable, including generators.
from itertools import pairwise
def gen():
yield from [1, 2, 3, 4]
print(list(pairwise(gen()))) # [(1, 2), (2, 3), (3, 4)]If you need to pair elements with a step other than one, pairwise is not the right tool. For example, to compare every second element, you would combine islice with zip or use a custom generator.
Practical Use Cases
Beyond simple differences, pairwise is useful in several common programming tasks:
- Detecting transitions in a sequence, such as finding where a boolean value flips.
- Grouping consecutive equal elements by comparing adjacent pairs.
- Computing moving averages or sliding-window calculations with a window size of two.
- Validating that a sequence is strictly increasing or decreasing.
Here is an example that finds all indices where a value changes:
from itertools import pairwise
def change_indices(items):
return [i for i, (a, b) in enumerate(pairwise(items), 1) if a != b]
print(change_indices([1, 1, 2, 2, 3])) # [2, 4]The enumerate starts at 1 because the first pair corresponds to the boundary between index 0 and index 1.
Compatibility and Python Versions
itertools.pairwise was added in Python 3.10. If you are working in an environment that uses an older Python version, you can implement the same behavior with zip and itertools.islice:
from itertools import islice
def pairwise_legacy(iterable):
a, b = islice(iterable, None, None), islice(iterable, 1, None)
return zip(a, b)However, this sequence-based version is reliable only when the input can be iterated more than once, such as a list. If the input is a one-shot iterator, the two islice wrappers share the same underlying iterator and produce the wrong result. A more robust equivalent for older Python versions is:
def pairwise_legacy(iterable):
it = iter(iterable)
prev = next(it, None)
for curr in it:
yield prev, curr
prev = currThis version works with any iterable and preserves the lazy, memory-efficient behavior. If you control the Python version in your project, using the built-in pairwise is cleaner and less error-prone. For code that must run on Python 3.9 or earlier, the manual implementation is a straightforward substitute.
When upgrading to Python 3.10 or later, you can replace manual loops or zip-based patterns with pairwise to simplify the code and reduce the chance of off-by-one errors. The function is small but fits naturally into the itertools family of composable, lazy tools.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.