slice iterator?

Paul Rubin http
Fri May 8 23:29:51 EDT 2009


Ross <ross.jett at gmail.com> writes:
> I have a really long list that I would like segmented into smaller
> lists. Let's say I had a list a = [1,2,3,4,5,6,7,8,9,10,11,12] and I
> wanted to split it into groups of 2 or groups of 3 or 4, etc. Is there
> a way to do this without explicitly defining new lists? 

That question comes up so often it should probably be a standard
library function.

Anyway, here is an iterator, if that's what you want:

   >>> from itertools import islice
   >>> a = range(12)
   >>> xs = iter(lambda x=iter(a): list(islice(x,3)), [])
   >>> print list(xs)
   [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]

Of course, as the saying goes, there's more than one way to do it ;-)



More information about the Python-list mailing list