flonk flonk - 2 years ago 265
Python Question

Iterate over all pairs of consecutive items from a given list

Given a list

l = [1,7,3,5]

I want to iterate over all pairs of consecutive list items
, i.e.

for i in xrange(len(l)-1):
# do something

I would like to do this in a more compact way, like
for (x,y) in someiterator(l): ...
is there a way to do do this using some builtin python iterators? I'm sure the
module should have a solution, but I just can't figure it out...

Answer Source

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

As 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:]):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download