def iterwhile(func, iterator):
    """Iterate for as long as func(value) returns true."""
    iterator = iter(iterator)
    while 1:
        next = iterator.next()
        if not func(next):
            raise StopIteration
        yield next
Iterate for as long as func(value) returns true.
recipes/Python/66448_Iterator_Utilities/recipe-66448.py