How to chop list n-elements at a time

Alex Martelli aleaxit at yahoo.com
Sat Jan 20 06:58:31 EST 2001


<cpsoct at my-deja.com> wrote in message news:94bjs8$5nn$1 at nnrp1.deja.com...
    [snip]
> 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]]

def bunch(list, N):
    templist = list + [None]*N
    result = []
    for i in range(0, len(list),N):
        result.append(templist[i:i+N])
    return result

or, more concisely:

def bunch(list, N):
    templist = list + [None]*N
    return [templist[i:i+N] for i in range(0, len(list), N)]


The 'templist' is only needed because you want the last sublist
padded with copies of None to the specified length N, rather
than possibly shorter than N.

You could alternatively just perform such padding at the end,
e.g. in the second form:

def bunch(list, N):
    result = [list[i:i+N] for i in range(0, len(list), N)]
    result[-1] = (result[-1]+[None]*N)[:N]
    return result

but it seems to me that the templist approach is a little bit
simpler/clearer (although it will potentially use a bit more
memory in some cases).


Alex






More information about the Python-list mailing list