Elegantly subsplitting a sequence

Steven Taschuk staschuk at telusplanet.net
Fri May 30 12:43:07 EDT 2003


Quoth Steve McAllister:
> The purpose being: {
> subsplit(range(11), groupby=3)
> -> [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10)]
> 
> }, do you think of more beautiful a way than {
> 
> def subsplit(seq, groupby=1):
>      return [tuple(seq[i:i+groupby])
>              for i in range(0, len(seq), groupby)]
> }?

That's what I usually do for this problem.  If you want to handle
arbitrary iterables, though, then something like

    def subsplit(iterable, groupsize=1):
        it = iter(iterable)
        try:
            while True:
                portion = []
                for _ in range(groupsize):
                    portion.append(it.next())
                yield tuple(portion)
        finally:
            if portion:
                yield tuple(portion)

might be preferable.

  [...]
-- 
Steven Taschuk             "The world will end if you get this wrong."
staschuk at telusplanet.net     -- "Typesetting Mathematics -- User's Guide",
                                 Brian Kernighan and Lorrinda Cherry





More information about the Python-list mailing list