splitting a list into n groups

Tim Hochberg tim.hochberg at ieee.org
Wed Oct 8 13:55:19 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 =
> lengthof list/5)
> 
> I have done this by a simple for loop and using indexes into the list.
> But it does'nt seemm very elegant

Depending on what you're doing, this may or may not be appropriate, but 
you might want to look at Numeric (or it's eventual successor numarray). 
In this case, you could use reshape to map your list into a n by x 
array, which you can treat like a nested list with respect to indexing.

 >>> import Numeric
 >>> data = range(25)
 >>> split = Numeric.reshape(data, (5,5))
 >>> split
array([[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19],
        [20, 21, 22, 23, 24]])
 >>> split[0]
array([0, 1, 2, 3, 4])
 >>> list(split[4])
[20, 21, 22, 23, 24]


You can sometimes use Numeric with nonnumeric data, but it tends to be 
quircky and often is not worth the trouble, but if you've got numeric 
data, try it out.

-tim





More information about the Python-list mailing list