How do I split a list of arbitrary length into equal sized chunks?
See also: How to iterate over a list in chunks.
To chunk strings, see Split string every nth character?.
chunkslistpythonsplit
How do I split a list of arbitrary length into equal sized chunks?
See also: How to iterate over a list in chunks.
To chunk strings, see Split string every nth character?.
Best Answer
Here's a generator that yields evenly-sized chunks:
For Python 2, using
xrange
instead ofrange
:Below is a list comprehension one-liner. The method above is preferable, though, since using named functions makes code easier to understand. For Python 3:
For Python 2: