How to chop list n-elements at a time

Fredrik Lundh fredrik at effbot.org
Sat Jan 20 07:16:49 EST 2001


Kevin Parks wrote:
> I've been at this a while and can't seem to get it to work. I am
> wondering if others know how, have tried, or already have written a
> func to package up list elements in sublists n at a time.
>
> I was able to get something that worked for bunches of 1, or 2, but i
> am wondering how to make the tool more general so that i could say:
>
> x=[1,2,3,4,5,6,7,8,9]
>
> bunch(x,1) --> [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
> bunch(x, 2) --> [[1,2], [3,4], [5,6], [7,8], [9, None]
> bunch(x, 3) --> [[1,2,3], [4,5,6], [7,8,9]]
> bunch(x, 4) --> [1,2,3,4], [5,6,7,8] [9, None, None, None]]

how about:

def bunch(mylist, times):
    out = [mylist[i:i+times] for i in range(0, len(mylist), times)]
    if out:
        out[-1].extend([None] * (times - len(out[-1])))
    return out

Cheers /F

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->






More information about the Python-list mailing list