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
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
.
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With