Better Iteration in Python— 6 Ways to Filter Iterables
5. Conditional Abortion

Suppose that you start with an iterable, and for particular business needs, you need to iterate it and the iteration doesn’t stop until some condition is met. In this case, you should consider using a function called takewhile, which is also a higher-order function that is available in the itertools module. Let’s see its usage with some example code before I explain it to you.

Use of takewhile Function

In the above code, we have a stream of HTTP responses with the code and data saved. We want to log all valid responses until we encounter an error. To do that, we use the takewhile function with a predicate or evaluation function lambda x: x[0] == 200 , which means that the iteration will continue to run until the first element in the iterator can’t satisfy this evaluation criterion. In our case, the first three elements are eligible, while the fourth one isn’t. Thus, the iteration will abort at the fourth position.

One thing that can be confusing to beginners is how it’s different from the filter function. The filter function will go over the entire iterable and keep all the elements that pass the evaluation criterion. By contrast, the takewhile function has the conditional abortion feature, and it will stop the iteration completely once the next item evaluates True for the predicate.
['Yong Cui']
['Python', 'Artificial Intelligence', 'Technology', 'Data Science', 'Programming']