CKTIS / Python
itertools.takewhile
Yields consecutive input items while a predicate holds.
Version: Python 3.14; repository image, production runtime not attested
Syntax
itertools.takewhile(predicate, iterable, /)Yields consecutive input items while a predicate holds.
The first failing item is consumed during the test and is unavailable in the remaining iterator.
For n < 3 the iterator yields 1 and 2, then reads 4 in order to test it. Four fails, so takewhile finishes without yielding it. Because the test already consumed 4, resuming the original iterator reveals only the final 1.
import itertools as I
it = iter([1, 2, 4, 1])
assert list(I.takewhile(lambda n: n < 3, it)) == [1, 2]
assert list(it) == [1]
Examples
import itertools as I
it = iter([1, 2, 4, 1])
print(list(I.takewhile(lambda n: n < 3, it)))
print(list(it))
Result
[1, 2] [1]
For n < 3 the iterator yields 1 and 2, then reads 4 in order to test it. Four fails, so takewhile finishes without yielding it. Because the test already consumed 4, resuming the original iterator reveals only the final 1.