Elegantly subsplitting a sequence

Steven Taschuk staschuk at telusplanet.net
Fri May 30 15:39:09 EDT 2003


Quoth I:
  [...]
>     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.

Heh.  Except that that code won't compile.  Fixed:

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

-- 
Steven Taschuk                               staschuk at telusplanet.net
"What I find most baffling about that song is that it was not a hit."
                                          -- Tony Dylan Davis (CKUA)





More information about the Python-list mailing list