Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
Hi,
I would like to split a list in many list of a length of x elements, like:
a = (1, 2, 3, 4, 5)
and get :
b = (
(1,2),
(3,4),
(5,)
)
if the length is set to 2 or :
b = (
(1,2,3),
(4,5)
)
if the length is equal to 3 ...
Is there a nice way to write this ? Otherwise I think the best way is to write it using an iterator ...
Here's how I'd do it. Iteration, but in a list comprehension. Note the type gets mixed; this may or may not be desired.
Usage:
Of course, you can easily make it produce a
tuple
too if you want - replace the list comprehension[...]
withtuple(...)
. You could also replaceseq[i:i + length]
withtuple(seq[i:i + length])
orlist(seq[i:i + length])
to make it return a fixed type.From the python docs on the itertools module:
Example:
The itertools module documentation. Read it, learn it, love it.
Specifically, from the recipes section:
Which gives:
which isn't quite what you want...you don't want the
None
in there...so. a quick fix:If you don't like typing the list comprehension every time, we can move its logic into the function:
Which gives:
Done.