splitting a list into n groups

Robert Brewer fumanchu at amor.org
Wed Oct 8 16:06:47 EDT 2003


Rajarshi Guha wrote:
> Hi, is there an efficient (pythonic) way in which I could split a list
into
> say 5 groups? By split I mean the the first x members would be one
group,
> the next x members another group and so on 5 times. (Obviously x =
> length of list/5)
> I have done this by a simple for loop and using indexes into the list.
> But it doesn't seem very elegant

I think you'll find for this issue, that there is a certain basic
complexity to the operation you want. You can reduce the logic only so
far, after which point, solutions become more clever than elegant.
Here's a list comprehension solution:

>>> aList = [x for x in range(18)]
>>> aList
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
>>> numberOfSubLists = 4
>>> subListLength, aMod = divmod(len(aList), numberOfSubLists)
>>> if aMod != 0: subListLength += 1
... 
>>> [aList[i:i + subListLength] for i in range(0, len(aList),
subListLength)]
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17]]

..which probably just rearranges the expressions you have in your
solution. By the way, I assumed a requirement of the system would be to
leave the last sublist short, if need be. I don't believe this is any
*clearer* than a multiple-statement for loop.

Some sort of extended indexing syntax would be nice, where one could
rewrite our last line as:

>>> aList[::subListLength]
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17]]


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org





More information about the Python-list mailing list