Given a list
l = [1, 7, 3, 5]
I want to iterate over all pairs of consecutive list items (1,7), (7,3), (3,5)
, i.e.
for i in xrange(len(l) - 1):
x = l[i]
y = l[i + 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 builtin Python iterators? I'm sure the itertools
module should have a solution, but I just can't figure it out.
I would create a generic
grouper
generator, like thisSample run 1
Output
Sample run 1
Output
Look at
pairwise
at itertools recipes: http://docs.python.org/2/library/itertools.html#recipesQuoting from there:
A General Version
A general version, that yields tuples of any given positive natural size, may look like that:
Just use zip
As suggested you might consider using the
izip
function initertools
for very long lists where you don't want to create a new list.You could use a
zip
.Just like a zipper, it creates pairs. So, to to mix your two lists, you get:
Then iterating goes like
If you wanted something inline but not terribly readable here's another solution that makes use of generators. I expect it's also not the best performance wise :-/
Convert list into generator with a tweak to end before the last item:
Convert it into pairs:
That's all you need.