What does the takewhile() function from the itertools module do?

The takewhile() function from the itertools module creates an iterator that returns elements from an iterable as long as the specified condition is true (evaluates to True or 1). Once the condition becomes false, the iterator stops and no more elements are returned.

In the example, takewhile it will return elements from the list my_list as long as they are less than five. When an element equal to or greater than five is encountered, the iteration stops.

from itertools import takewhile

my_list = [1, 3, 5, 7, 2, 4, 6]
print(list(takewhile(lambda x: x < 5, my_list)))

Comments (0)

Leave a comment