Home >Backend Development >Python Tutorial >How Can I Iterate Over Lists in Pairs or Groups in Python?
Pairwise Iteration Over Lists
Iterating over elements in pairs is a common requirement when manipulating lists. However, the standard for loops and list comprehensions in Python don't provide a built-in solution for pairwise traversal.
Pairwise Implementation
To overcome this limitation, a custom function called pairwise() can be implemented. This function takes an iterable as input and returns pairs of elements.
def pairwise(iterable): "s -> (s0, s1), (s2, s3), (s4, s5), ..." a = iter(iterable) return zip(a, a)
Usage
Using this pairwise() function, you can iterate over elements in pairs as follows:
l = [1, 2, 3, 4, 5, 6] for x, y in pairwise(l): print("{} + {} = {}".format(x, y, x + y))
Output:
1 + 2 = 3 3 + 4 = 7 5 + 6 = 11
Generalized Grouping
For cases where you need to iterate over elements in groups of any size, a more generalized function called grouped() can be used.
def grouped(iterable, n): "s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), (s2n,s2n+1,s2n+2,...s3n-1), ..." return zip(*[iter(iterable)] * n)
Usage
for x, y in grouped(l, 2): print("{} + {} = {}".format(x, y, x + y))
Type Checking with Mypy
For Python 3 users wishing to perform type checking with Mypy, the grouped() function can be annotated as follows:
from typing import Iterable, Tuple, TypeVar T = TypeVar("T") def grouped(iterable: Iterable[T], n=2) -> Iterable[Tuple[T, ...]]: """s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), ...""" return zip(*[iter(iterable)] * n)
The above is the detailed content of How Can I Iterate Over Lists in Pairs or Groups in Python?. For more information, please follow other related articles on the PHP Chinese website!