Home >Backend Development >Python Tutorial >How Can I Iterate Through a List in Pairs or Groups of Elements?
Loop through Every Two Elements in a List
Iterating over every two adjacent elements in a list can be achieved with the help of specialized functions or techniques. Here's how you can accomplish this task:
Using pairwise() or grouped() Function:
This method employs functions that provide a pairwise or grouped iteration over the list.
Implementation and Usage:
For example, to iterate over pairs of elements in a list and print their sum:
from typing import Iterable, Tuple, TypeVar T = TypeVar("T") def pairwise(iterable: Iterable[T]) -> Iterable[Tuple[T, T]]: """s -> (s0, s1), (s2, s3), ...""" a = iter(iterable) return zip(a, a) l = [1, 2, 3, 4, 5, 6] for x, y in pairwise(l): print(f"{x} + {y} = {x + y}")
This approach provides efficient iteration and avoids unnecessary list duplication.
The above is the detailed content of How Can I Iterate Through a List in Pairs or Groups of Elements?. For more information, please follow other related articles on the PHP Chinese website!