# How to group elements in python by n elements? [duplicate]

Posted on

### Question :

How to group elements in python by n elements? [duplicate]

Possible Duplicate:
How do you split a list into evenly sized chunks in Python?

I’d like to get groups of size n elements from a list l:

ie:

``````[1,2,3,4,5,6,7,8,9] -> [[1,2,3], [4,5,6],[7,8,9]] where n is 3
``````

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

``````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)
``````

Well, the brute force answer is:

``````subList = [theList[n:n+N] for n in range(0, len(theList), N)]
``````

where `N` is the group size (3 in your case):

``````>>> theList = list(range(10))
>>> N = 3
>>> subList = [theList[n:n+N] for n in range(0, len(theList), N)]
>>> subList
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
``````

If you want a fill value, you can do this right before the list comprehension:

``````tempList = theList + [fill] * N
subList = [tempList[n:n+N] for n in range(0, len(theList), N)]
``````

Example:

``````>>> fill = 99
>>> tempList = theList + [fill] * N
>>> subList = [tempList[n:n+N] for n in range(0, len(theList), N)]
>>> subList
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 99, 99]]
``````

See examples at the bottom of the itertools docs: http://docs.python.org/library/itertools.html?highlight=itertools#module-itertools

You want the “grouper” method, or something like it.

``````a = range(1,10)
``````answer = [L[3*i:(3*i)+3] for i in range((len(L)/3) +1)]