takewhile And dropwhile Slice By Predicate
dropwhile skips a leading run that satisfies the predicate and takewhile keeps only that run; both stop at the first mismatch, unlike filter.
Code
from itertools import dropwhile, takewhile
lines = ["# header", "# owner: ci", "", "alpha=1", "beta=2"]
# dropwhile skips the leading run of satisfying items: once the predicate is false, everything else passes through as-is
data = list(dropwhile(lambda line: line.startswith("#") or line == "", lines))
print("data:", data)
scores = [92, 88, 59, 76]
# takewhile keeps only the leading run that satisfies the predicate: it stops entirely the moment 59 shows up
head = list(takewhile(lambda score: score >= 60, scores))
print("takewhile:", head)
# filter skips unqualified items and keeps collecting: different from takewhile's prefix-only semantics
print("filter :", list(filter(lambda score: score >= 60, scores)))Following what executes
The file’s state is a handful of top-level bindings: lines, data, scores, head.
Putting it to use
Running the file prints labeled results such as data:, takewhile:, filter : — each operation’s effect is visible in the output.
Interactive Tools for This Topic
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. Every import resolves inside the standard library — `itertools`. Its state lives in module-level bindings: `lines`, `data`, `scores`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.