Consecutive Pairs in a List Using Built-in Python Iterators
Given a list and a desire to loop over pairs of consecutive items, such as (1,7) and (7,3), examining the itertools module for a solution comes to mind. However, a more efficient way to achieve this with built-in Python iterators exists.
The zip function seamlessly pairs consecutive elements from two sequences, creating a tuple for each pair. By supplying the input list both as the first and second arguments to zip, we obtain a generator that yields tuples containing pairs of consecutive items. For instance, for l = [1, 7, 3, 5], the output will be:
(1, 7) (7, 3) (3, 5)
In Python 2, consider employing izip from itertools for exceptionally long lists to optimize performance and prevent list creation.
The above is the detailed content of How to Iterate Over Consecutive Pairs in a List Using Built-in Python Iterators?. For more information, please follow other related articles on the PHP Chinese website!