Skip to content

Two methods for fast pairing lists in Python

In Python, there are two commonly used methods for quickly pairing lists.


Before 3.10, the zip function combined with slicing in Python was used to pair elements. The zip() function takes two or more lists as input and returns a new list of tuples, where each tuple contains elements from the corresponding positions of the input lists. This method is useful when you want to iterate over multiple lists simultaneously.

list1 = [1, 2, 3]
list2 = ['A', 'B', 'C']
pairs = list(zip(list1, list2))

The resulting pairs list will be [(1, 'A'), (2, 'B'), (3, 'C')].


In 3.10, you can now use pairwise() from itertools:

from itertools import pairwise

numbers = range(1, 6)
pairs = list(pairwise(numbers))
print(pairs)  # [(1, 2), (2, 3), (3, 4), (4, 5)]

The itertools.pairwise() method is more versatile and can be applied to any iterable object. It is slightly more complex than the zip() method but provides greater flexibility for different iterable types.

It is particularly useful for sliding window problems, such as sliding window problems in data analysis or sequence processing.