Home >Backend Development >Python Tutorial >How Can I Iterate Over Pairs (or Groups) of Elements in a Python List?

How Can I Iterate Over Pairs (or Groups) of Elements in a Python List?

Susan Sarandon
Susan SarandonOriginal
2024-12-10 15:55:13698browse

How Can I Iterate Over Pairs (or Groups) of Elements in a Python List?

Iterating over Pairs of Elements in a List

When iterating over a list, we often encounter situations where we require access to two elements at a time. To address this, we can utilize the concept of pairwise iteration.

Python's built-in zip() function can assist us in this regard. The pairwise() or grouped() method consumes an iterable and yields successive two-element subsequences. Here's how we can implement it:

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

Using this function, let's consider the list [1, 2, 3, 4, 5, 6]. To demonstrate pairwise iteration:

for x, y in pairwise(l):
   print("%d + %d = %d" % (x, y, x + y))

This will produce the following output:

1 + 2 = 3
3 + 4 = 7
5 + 6 = 11

Alternatively, the grouped() function allows us to iterate over n elements at a time. Here's an implementation:

def grouped(iterable, n=2):
    "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, with n set to 3, we can iterate over three elements at a time:

for x, y, z in grouped(l, 3):
   print("%d + %d + %d = %d" % (x, y, z, x + y + z))

This approach is efficient as it iterates over the list only once and eliminates the need for intermediate lists.

The above is the detailed content of How Can I Iterate Over Pairs (or Groups) of Elements in a Python List?. 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