Fix Python – Iterate through pairs of items in a Python list [duplicate]

Question

Asked By – marvin_yorke

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]

Now we will see solution for issue: Iterate through pairs of items in a Python list [duplicate]


Answer

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

This question is answered By – Jochen Ritzel

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0