Alex Rivera | Logout

How to group elements in python by n elements

Asked 2011-02-14T23:13:12.970
61

Given a list [1,2,3,4,5,6,7,8,9,10,11,12] and a specified chunk size (say 3), how can I get a list of chunks [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]?

Edit
Report

1 Answer

41

You can use the grouper function from the recipes in the itertools documentation:

from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
    """Collect data into fixed-length chunks or blocks.

    >>> grouper('ABCDEFG', 3, 'x')
    ['ABC', 'DEF', 'Gxx']
    """
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)
answered 2011-02-14T23:17:24.867

Your Answer