my list is:
mylist=[1,2,3,4,5,6]
I would like to convert mylist into a list of pairs:
[[1,2],[3,4],[5,6]]
Is there a pythonic way of doing so? List comprehension? Itertools?
Yeppers, list comprehension is my usual way of doing it:
>>> groupsize = 2
>>> [mylist[x:x+groupsize] for x in range(0,len(mylist),groupsize)]
[[1,2],[3,4],[5,6]]
>>> groupsize = 3
>>> [mylist[x:x+groupsize] for x in range(0,len(mylist),groupsize)]
[[1,2,3],[4,5,6]]
I use range
for portability, if you are using python 2 (you probably are) change the range
to xrange
to save memory.
My preferred technique:
>>> mylist = [1, 2, 3, 4, 5, 6]
>>> mylist = iter(mylist)
>>> zip(mylist, mylist)
[(1, 2), (3, 4), (5, 6)]
I usually use generators instead of lists anyway, so line 2 usually isn't required.
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