waitingkuo
waitingkuo

Reputation: 93854

Is any elegant way to make a list contains some integers to become a list contains some tuples?

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

Answers (5)

pradyunsg
pradyunsg

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

rurouniwallace
rurouniwallace

Reputation: 2087

b = []
for i in range(0,len(a),2):
    b.append((a[i],a[i+1]))
a = b

Upvotes: 1

Benjamin
Benjamin

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

Hunter McMillen
Hunter McMillen

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

georg
georg

Reputation: 214979

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

is a common idiom

Upvotes: 9

Related Questions