Home >Backend Development >Python Tutorial >How Can I Iterate Through Adjacent Pairs in a Python List?

How Can I Iterate Through Adjacent Pairs in a Python List?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-21 04:28:10884browse

How Can I Iterate Through Adjacent Pairs in a Python List?

Iterating Through Adjacent Pairs in a Python List

Many programming problems can be solved by iterating over adjacent pairs of items in a sequence. For example, you may need to compare consecutive elements, sum them up, or perform some other operation on neighboring values.

Consider the following list of numbers:

a = [5, 7, 11, 4, 5]

You want to iterate over this list in a way that allows you to access consecutive elements as a pair. Python doesn't provide a built-in way to do this, but it can be achieved using the zip function:

for previous, current in zip(a, a[1:]):
    print(previous, current)

The zip function takes multiple iterables (such as lists or tuples) and returns a new iterable that contains tuples of corresponding elements from each input iterable. In this case, we're zipping the original list a with a copy of itself starting from the second element (a[1:]). This gives us pairs of consecutive elements from the original list.

The output of the above code will be:

5 7
7 11
11 4
4 5

Note that this technique works even if the list is empty or has only one element. In such cases, zip will return an empty iterable, and the code inside the for loop will never execute.

The above is the detailed content of How Can I Iterate Through Adjacent Pairs 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