Splitting a list into even size chunks in python?

Arnaud Delobelle arnodel at gmail.com
Wed Mar 27 21:19:05 CET 2013


On 27 March 2013 08:27, Peter Otten <__peter__ at web.de> wrote:

> Look again, for the grouper() recipe. For lists you can also use slicing:
>
>>>> items
> ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>>> n = 3
>>>> [items[start:start+n] for start in range(0, len(items), n)]
> [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]

Another way with islice (so it works for any iterable):

>>> from itertools import islice
>>> items = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> n = 3
>>> list(iter(lambda i=iter(items):list(islice(i, n)),[]))
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]

Not too readable though :)

-- 
Arnaud



More information about the Python-list mailing list