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]]
?
Asked
Active
Viewed 9.4k times
5 Answers
57
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]]

David Avsajanishvili
- 7,678
- 2
- 22
- 24

Mike DeSimone
- 41,631
- 10
- 72
- 96
39
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)

Nuno André
- 4,739
- 1
- 33
- 46

Mark Byers
- 811,555
- 193
- 1,581
- 1,452
-
1I think this is the best way to do this. However, a more helpful answer would link here: http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks/434411#434411 , since it includes some discussion as to why this works. – phooji Feb 14 '11 at 23:38
6
How about
a = range(1,10)
n = 3
out = [a[k:k+n] for k in range(0, len(a), n)]

michael_j_ward
- 4,369
- 1
- 24
- 25

sizzzzlerz
- 4,277
- 3
- 27
- 35
-
Did you test this? I don't think `[[1, 4, 7], [4], [7]]` is the desired output. – Andrew Clark Feb 14 '11 at 23:22
-
2Remove the extra `:` in the `[]` operation. It's the same answer as the first part of mine. – Mike DeSimone Feb 14 '11 at 23:25
5
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.

Adam Vandenberg
- 19,991
- 9
- 54
- 56
0
answer = [L[3*i:(3*i)+3] for i in range((len(L)/3) +1)]
if not answer[-1]:
answer = answer[:-1]

inspectorG4dget
- 110,290
- 27
- 149
- 241