Skip to content

Split a list into evenly sized chunks in Python

def chunks(l, n):
    n = max(1, n)
    return (l[i:i+n] for i in range(0, len(l), n))

where l is the list and n is the number of items in a chunk.

Advertisements

Use xrange() instead of range() in the case of Python 2.x

See also  TypeError: 'str' object does not support item assignment - Python error - How to fix?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.