Possible Duplicate:
Iterate a list as pair (current, next) in Python
I have a list like this:
list = [A, B, C, D, E, F, G]
How can I group this to get the following Python output
[(A,B), (B,C), (C, D), (D,E), (E,F), (F,G)]
So the values are grouped by the secound value but the order is preserved...
use a list comprehension that iterates from 0 to length - 1
or even better , just use zip
Try using
zip()
:Also, you shouldn't use the name
list
, as you will override the built-in list type.Example:
For a version that will work with generators or other one-pass iterables, you can use the pairwise recipe from the itertools docs: