better way to write this function

Paul McGuire ptmcg at austin.rr.com
Mon Nov 26 12:16:07 EST 2007


On Nov 26, 1:42 am, Kelie <kf9... at gmail.com> wrote:
> Hello,
>
> This function does I what I want. But I'm wondering if there is an
> easier/better way. To be honest, I don't have a good understanding of
> what "pythonic" means yet.
>
> def divide_list(lst, n):
>     """Divide a list into a number of lists, each with n items. Extra
> items are
>        ignored, if any."""
>     cnt = len(lst) / n
>     rv =  [[None for i in range(n)] for i in range(cnt)]
>     for i in range(cnt):
>         for j in range(n):
>             rv[i][j] = lst[i * n + j]
>     return rv
>
> Thanks!

>>> lst = list("ABCDE")
>>> for j in range(1,6):
...     print j,':',[lst[i:i+j] for i in xrange(0,len(lst),j)]
...
1 : [['A'], ['B'], ['C'], ['D'], ['E']]
2 : [['A', 'B'], ['C', 'D'], ['E']]
3 : [['A', 'B', 'C'], ['D', 'E']]
4 : [['A', 'B', 'C', 'D'], ['E']]
5 : [['A', 'B', 'C', 'D', 'E']]

Or if you want to discard the uneven leftovers:

>>> for j in range(1,6):
...     print j,':',[lst[i:i+j] for i in xrange(0,len(lst),j) if i
+j<=len(lst)]
...
1 : [['A'], ['B'], ['C'], ['D'], ['E']]
2 : [['A', 'B'], ['C', 'D']]
3 : [['A', 'B', 'C']]
4 : [['A', 'B', 'C', 'D']]
5 : [['A', 'B', 'C', 'D', 'E']]

Or define a lambda:

>>> chunksWithLeftovers = lambda lst,n: [lst[i:i+n] for i in xrange(0,len(lst),n)]
>>> chunksWithoutLeftovers = lambda lst,n: [lst[i:i+n] for i in xrange(0,len(lst),n) if i+n<=len(lst)]
>>> chunksWithLeftovers(lst,2)
[['A', 'B'], ['C', 'D'], ['E']]
>>> chunksWithoutLeftovers(lst,2)
[['A', 'B'], ['C', 'D']]


-- Paul



More information about the Python-list mailing list