breaking up a list

Peter Otten __peter__ at web.de
Tue Sep 28 13:58:57 CEST 2004


> If I have a list, say
> 
> x=[1,2,3,4,5,6]
> 
> What's the best way of converting it into this: [[1, 2], [3, 4], [5, 6]],
> i.e. splitting it into pairs.

I like

>>> x = [1, 2, 3, 4, 5, 6]
>>> it = iter(x)
>>> zip(it, it) 
[(1, 2), (3, 4), (5, 6)]

even after posting it several times before :-) Use map(list, zip(it, it)) if
you need lists instead of tuples.

Michele Simionato has posted a generalized version of this recipe:
http://mail.python.org/pipermail/python-list/2004-May/222673.html

Peter




More information about the Python-list mailing list