On this page
itertools.takewhile
Prev: itertools.starmap | Up: itertools | Next: itertools.tee
Rel: itertools.accumulate, itertools.batched, itertools.chain, itertools.combinations
Ref: docs.python.org — itertools.takewhile
Tags: #public #python3 #stdlib #itertools
Import
import itertools
from itertools import takewhile
Signature & Overview
itertools.takewhile(predicate, iterable, /)
Return successive entries from an iterable as long as the predicate evaluates to true for each entry.
Usage
from itertools import takewhile
# Yields leading elements < 5 and stops immediately at 6
assert list(takewhile(lambda x: x < 5, [1, 4, 6, 2, 8])) == [1, 4]
Gotchas
- Stops at the first falsy element:
2is never reached after6fails the predicate. - Consumes the failing element: If you reuse the underlying iterator after
takewhilestops, the first element that failed the predicate (6) has already been pulled from it.
REPL Inspect
from itertools import takewhile
help(takewhile)
Linked from
Related notes
- tuts/python3/stdlib_module/itertools/starmap Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/tee Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools/accumulate Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/batched Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/chain Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/combinations Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/combinations_with_replacement shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/compress shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/count shared tags: #itertools, #stdlib