Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collect every pair of elements from a list into tuples in Python [duplicate]

Tags:

Possible Duplicate:
Pairs from single list

I have a list of small integers, say:

[1, 2, 3, 4, 5, 6] 

I wish to collect the sequential pairs and return a new list containing tuples created from those pairs, i.e.:

[(1, 2), (3, 4), (5, 6)] 

I know there must be a really simple way to do this, but can't quite work it out.

Thanks

like image 476
TartanLlama Avatar asked Jan 10 '11 12:01

TartanLlama


2 Answers

Well there is one very easy, but somewhat fragile way, zip it with sliced versions of itself.

zipped = zip(mylist[0::2], mylist[1::2]) 

In case you didn't know, the last slice parameter is the "step". So we select every second item in the list starting from zero (1, 3, 5). Then we do the same but starting from one (2, 4, 6) and make tuples out of them with zip.

like image 58
Skurmedel Avatar answered Oct 14 '22 06:10

Skurmedel


Apart from the above answers, you also need to know the simplest of way too (if you hadn't known already)

l = [1, 2, 3, 4, 5, 6] o = [(l[i],l[i+1]) for i in range(0,len(l),2)] 
like image 44
Senthil Kumaran Avatar answered Oct 14 '22 06:10

Senthil Kumaran