Iterate through pairs of items in a Python list

PythonListLoops

Python Problem Overview


Is it possible to iterate a list in the following way in Python (treat this code as pseudocode)?

a = [5, 7, 11, 4, 5]
for v, w in a:
    print [v, w]

And it should produce

[5, 7]
[7, 11]
[11, 4]
[4, 5]

Python Solutions


Solution 1 - Python

You can zip the list with itself sans the first element:

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

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

This works even if your list has no elements or only 1 element (in which case zip returns an empty iterable and the code in the for loop never executes). It doesn't work on generators, only sequences (tuple, list, str, etc).

Solution 2 - Python

From the itertools recipes:

from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

for v, w in pairwise(a):
    ...

Solution 3 - Python

To do that you should do:

a =  [5, 7, 11, 4, 5]
for i in range(len(a)-1):
    print [a[i], a[i+1]]

Solution 4 - Python

Nearly verbatim from https://stackoverflow.com/questions/1257413/iterate-over-pairs-in-a-list-circular-fashion-in-python/1257446#1257446:

def pairs(seq):
    i = iter(seq)
    prev = next(i)
    for item in i:
        yield prev, item
        prev = item

Solution 5 - Python

>>> a = [5, 7, 11, 4, 5]
>>> for n,k in enumerate(a[:-1]):
...     print a[n],a[n+1]
...
5 7
7 11
11 4
4 5

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmarvin_yorkeView Question on Stackoverflow
Solution 1 - PythonhlukView Answer on Stackoverflow
Solution 2 - PythonJochen RitzelView Answer on Stackoverflow
Solution 3 - PythonSantiago AlessandriView Answer on Stackoverflow
Solution 4 - PythonGabeView Answer on Stackoverflow
Solution 5 - Pythonghostdog74View Answer on Stackoverflow