Iterate over all pairs of consecutive items in a list [duplicate]

Just use zip

>>> l = [1, 7, 3, 5]
>>> for first, second in zip(l, l[1:]):
...     print first, second
...
1 7
7 3
3 5

If you use Python 2 (not suggested) you might consider using the izip function in itertools for very long lists where you don’t want to create a new list.

import itertools

for first, second in itertools.izip(l, l[1:]):
    ...

Leave a Comment