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...
Try using zip()
:
zip(lst, lst[1:])
Also, you shouldn't use the name list
, as you will override the built-in list type.
Example:
>>> lst = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
>>> zip(lst, lst[1:])
[('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G')]
For a version that will work with generators or other one-pass iterables, you can use the pairwise recipe from the itertools docs:
from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
>>> a = [1,2,3,4,5]
>>> zip(a, a[1:])
<zip object at 0x7fe6e905ab90>
>>> list(zip(a, a[1:]))
[(1, 2), (2, 3), (3, 4), (4, 5)]
use a list comprehension that iterates from 0 to length - 1
print [(a[i],a[i+1]) for i in range(len(a)-1)]
or even better , just use zip
print zip (a,a[1:])