3

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)]
waitingkuo
  • 89,478
  • 28
  • 112
  • 118

5 Answers5

9
pairs = zip(*[iter(a)]*2)

is a common idiom

georg
  • 211,518
  • 52
  • 313
  • 390
6
[(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

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Benjamin
  • 609
  • 3
  • 8
3
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

Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
1
b = []
for i in range(0,len(a),2):
    b.append((a[i],a[i+1]))
a = b
rurouniwallace
  • 2,027
  • 6
  • 25
  • 47
0

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)]
pradyunsg
  • 18,287
  • 11
  • 43
  • 96