Home  >  Article  >  Backend Development  >  How to Iterate Over Consecutive Pairs in a List Using Built-in Python Iterators?

How to Iterate Over Consecutive Pairs in a List Using Built-in Python Iterators?

Barbara Streisand
Barbara StreisandOriginal
2024-11-08 07:50:01335browse

How to Iterate Over Consecutive Pairs in a List Using Built-in Python Iterators?

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!

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