Reputation: 93854
I have a list
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Is any elegant way to make them work in pair? My expected out is
[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
Upvotes: 3
Views: 135
Reputation: 19446
Try it using slices and zip.
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> zip(a[::2],a[1::2])
[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
Upvotes: 0
Reputation: 2087
b = []
for i in range(0,len(a),2):
b.append((a[i],a[i+1]))
a = b
Upvotes: 1
Reputation: 609
[(a[2*i], a[2*i+1] ) for i in range(len(a)/2)]
This is of course assuming that len(a) is an even number
Upvotes: 6
Reputation: 61510
def group(lst, n):
"""group([0,3,4,10,2,3], 2) => [(0,3), (4,10), (2,3)]
Group a list into consecutive n-tuples. Incomplete tuples are
discarded e.g.
>>> group(range(10), 3)
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
"""
return zip(*[lst[i::n] for i in range(n)])
From activestate, a recipe for n-tuples, not just 2-tuples
Upvotes: 3