splitting a list into n groups

Eddie Corns eddie at holyrood.ed.ac.uk
Wed Oct 8 14:38:45 EDT 2003


Rajarshi Guha <rajarshi at presidency.com> writes:

>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 =
>lengthof list/5)

How about:

------------------------------------------------------------
def span (x, n):
    return range(0, x, n)

def group (l, num):
    n = (len(l)/num) + 1
    return [l[s:s+n] for s in span (len(l), n)]

# test cases
l1 = range(100)
print group (l1, 5)
print group (l1, 6)
print group (l1, 4)
------------------------------------------------------------

Even though span could be folded in to make it shorter, abstracting it out
allows you to name and document what it does (return the start index of each
SPAN of n items).  Also it doesn't worry too much about the last list being
the same size as the rest.  I'm too lazy to check the boundary conditions
properly (an exercise for the reader).  A completely non lazy person would
possibly define the more primitive group_by_n:

def group_by_n (l, n):
    return [l[s:s+n] for s in span (len(l), n)]

and define group_into_num_pieces in terms of that:

def group_into_num_pieces (l, num):
    return group_by_n (l,(len(l)/num) + 1)

giving you 3 useful functions for the price of 1, but I'm too lazy for that.

Eddie





More information about the Python-list mailing list