Home >Backend Development >Python Tutorial >How Can I Iterate Through a List in Python Using Pairwise or N-Tuple Grouping?

How Can I Iterate Through a List in Python Using Pairwise or N-Tuple Grouping?

Barbara Streisand
Barbara StreisandOriginal
2024-12-09 10:58:12705browse

How Can I Iterate Through a List in Python Using Pairwise or N-Tuple Grouping?

Performing Pairwise Iteration in Lists

Problem:

In a given list, iterate over the elements in pairs to perform a specific operation.

Implementation:

A Pythonic approach for pairwise iteration is to employ the pairwise() or grouped() functions:

def pairwise(iterable):
    "s -> (s0, s1), (s2, s3), (s4, s5), ..."
    a = iter(iterable)
    return zip(a, a)

l = [1,2,3,4,5,6]
for x, y in pairwise(l):
    print("{} + {} = {}".format(x, y, x + y))

This function zips the iterable with itself, resulting in pairs of elements.

Generalized Grouping:

To group elements in n-tuples, use the grouped() function:

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)

For instance, to iterate over triples from the list l above:

for x, y, z in grouped(l, 3):
    print("{} + {} + {} = {}".format(x, y, z, x + y + z))

Type Checking with Mypy:

For type checking in Python 3 with Mypy:

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 Through a List in Python Using Pairwise or N-Tuple Grouping?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn