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 …
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
Nonein 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.