Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most pythonic (and efficient) way of nesting a list in pairs

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?

like image 523
jbastos Avatar asked Aug 03 '12 02:08

jbastos


2 Answers

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.

like image 120
Josiah Avatar answered Oct 06 '22 00:10

Josiah


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.

like image 28
robert king Avatar answered Oct 06 '22 01:10

robert king