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
  • 80,738
  • 23
  • 108
  • 117

5 Answers5

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

is a common idiom

georg
  • 204,715
  • 48
  • 286
  • 369
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
  • 55,177
  • 19
  • 133
  • 197
Benjamin
  • 611
  • 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
  • 56,682
  • 21
  • 115
  • 164
1
b = []
for i in range(0,len(a),2):
    b.append((a[i],a[i+1]))
a = b
rurouniwallace
  • 1,927
  • 6
  • 24
  • 45
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
  • 16,339
  • 10
  • 39
  • 91