Good use for itertools.dropwhile and itertools.takewhile

Chris Angelico rosuav at gmail.com
Wed Dec 5 14:45:05 CET 2012


On Wed, Dec 5, 2012 at 12:17 PM, Nick Mellor <thebalancepro at gmail.com> wrote:
>
> takewhile mines for gold at the start of a sequence, dropwhile drops the dross at the start of a sequence.

When you're using both over the same sequence and with the same
condition, it seems odd that you need to iterate over it twice.
Perhaps a partitioning iterator would be cleaner - something like
this:

def partitionwhile(predicate, iterable):
    iterable = iter(iterable)
    while True:
        val = next(iterable)
        if not predicate(val): break
        yield val
    raise StopIteration # Signal the end of Phase 1
    for val in iterable: yield val # or just "yield from iterable", I think

Only the cold hard boot of reality just stomped out the spark of an
idea. Once StopIteration has been raised, that's it, there's no
"resuming" the iterator. Is there a way around that? Is there a clean
way to say "Done for now, but next time you ask, there'll be more"?

I tested it on Python 3.2 (yeah, time I upgraded, I know).

ChrisA



More information about the Python-list mailing list