better way to write this function

Chris Mellon arkanes at gmail.com
Mon Nov 26 11:50:39 EST 2007


On Nov 26, 2007 3:24 AM, Paul Rudin <paul.nospam at rudin.co.uk> wrote:
> Kelie <kf9150 at gmail.com> writes:
>
> > 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!
>
> See the last recipe from:
> http://docs.python.org/lib/itertools-recipes.html. It's not doing
> quite the same thing, but gives an illustration of one way to approach
> this sort of thing.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

The one in the sample consumes the entire sequence up front, too. It's
trivial to write a fully generator based one (and only slightly more
work to implement an iterator that doesn't rely on generators, if you
want to avoid the slight performance hit), but there's a few subtle
issues and I too think that we really should have a good one ready for
use in itertools. Maybe I should write a patch.



More information about the Python-list mailing list