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  How to get hostname in Python?

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.