Search code examples
pythonlistiterationpython-itertoolslist-manipulation

Pythonic iteration over sliding window pairs in list?


What's the most Pythonic efficient way to iterate over a list in sliding pairs? Here's a related example:

>>> l
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> for x, y in itertools.izip(l, l[1::2]): print x, y
... 
a b
b d
c f

this is iteration in pairs, but how can we get iteration over a sliding pair? Meaning iteration over the pairs:

a b
b c
c d
d e
etc.

which is iteration over the pairs, except sliding the pair by 1 element each time rather than by 2 elements. thanks.


Solution

  • How about:

    for x, y in itertools.izip(l, l[1:]): print x, y