all Python 3itertoolsfunction
itertools.takewhile
itertools
Yield elements while the predicate is true, then stop.
Syntax
itertools.takewhile(predicate, iterable)
It stops for good at the first element where the predicate is false — unlike filter(), which merely skips non-matching items and keeps going (dropwhile is the mirror image). Note that the element that breaks the run is already pulled from the source iterator and lost if you keep reading that same iterator.
Examples
import itertools
print(list(itertools.takewhile(lambda x: x < 3, [1, 2, 3, 1]))) # → [1, 2]
print(''.join(itertools.takewhile(str.isdigit, '2026год'))) # → 2026
print(list(itertools.takewhile(lambda x: x > 0, [-1, 5, 7]))) # → []
print(list(filter(lambda x: x < 3, [1, 2, 3, 1]))) # → [1, 2, 1]
print(list(itertools.dropwhile(lambda x: x < 3, [1, 2, 3, 1]))) # → [3, 1]
See also
Open in the full glossarydocs.python.orgReport an inaccuracy