Iterate through pairs of items in a Python list

Question:

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]
Asked By: marvin_yorke

||

Answers:

Nearly verbatim from Iterate over pairs in a list (circular fashion) in Python:

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

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):
    ...
Answered By: Jochen Ritzel

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]]
Answered By: Santiago Alessandri
>>> 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
Answered By: ghostdog74

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).

Answered By: hluk
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.