49

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
Trenton McKinney
  • 43,885
  • 25
  • 111
  • 113
TheOne
  • 10,281
  • 20
  • 77
  • 116
  • Duplicate: http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python – phooji Feb 14 '11 at 23:20

5 Answers5

43

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,158
  • 2
  • 21
  • 24
Mike DeSimone
  • 40,052
  • 10
  • 71
  • 95
32

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)
AMC
  • 2,535
  • 7
  • 12
  • 34
Mark Byers
  • 767,688
  • 176
  • 1,542
  • 1,434
  • 1
    I 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
  • 3,903
  • 1
  • 21
  • 24
sizzzzlerz
  • 4,101
  • 3
  • 22
  • 34
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
  • 18,893
  • 7
  • 52
  • 55
0
answer = [L[3*i:(3*i)+3] for i in range((len(L)/3) +1)]
if not answer[-1]:
    answer = answer[:-1]
inspectorG4dget
  • 104,525
  • 25
  • 135
  • 234