In article <7xprejoswg....@ruckus.brouhaha.com>, Paul Rubin <http://phr...@nospam.invalid> wrote: > Ross <ross.j...@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 ;-)
python2.6 itertools introduces the izip_longest function and the grouper recipe <http://docs.python.org/library/itertools.html>: def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) -- Ned Deily, n...@acm.org -- http://mail.python.org/mailman/listinfo/python-list