Sub topic 6
Filtering streams with takewhile, dropwhile, filterfalse and compress
This chapter assumes you know how iterators are consumed and that lambda expressions can serve as predicates. A predicate is a function that returns true or false for an item. The four tools here filter lazily. They produce items on demand and never build an intermediate list.
Four tools at a glance
| Function | Keeps | Stops early? |
|---|---|---|
| `takewhile(pred, it)` | Items from the start, while `pred` is true | Yes, at the first failure |
| `dropwhile(pred, it)` | Everything after the leading items where `pred` is true | No |
| `filterfalse(pred, it)` | Items where `pred` is false | No |
| `compress(data, selectors)` | Items whose matching selector is true | When either input ends |
takewhile and dropwhile
Both react to the first item that fails the predicate. takewhile yields items until that point and then stops. dropwhile discards items until that point and then yields everything that remains.
from itertools import takewhile, dropwhile
values = [1, 4, 6, 2]
print(list(takewhile(lambda x: x < 5, values)))
print(list(dropwhile(lambda x: x < 5, values)))This prints [1, 4] and then [6, 2]. The 2 survives dropwhile even though it satisfies the predicate. Once dropping ends, the predicate is never checked again.
Because takewhile stops early, it can safely cut off an infinite stream:
from itertools import count, takewhile
squares = (n * n for n in count(1))
print(list(takewhile(lambda s: s < 50, squares)))This prints [1, 4, 9, 16, 25, 36, 49].
filterfalse
filterfalse is the complement of the built-in filter. It keeps the items for which the predicate is false. Passing None as the predicate keeps the items that are falsy.
from itertools import filterfalse
print(list(filterfalse(lambda x: x % 2, range(10))))
print(list(filterfalse(None, [0, 1, "", "a", None, []])))The output is [0, 2, 4, 6, 8] and then [0, '', None, []]. Use filterfalse when the rejecting condition is the natural one to write. That is clearer than negating a lambda.
compress
compress filters one iterable using a second iterable of flags. This helps when the selection was computed separately, for example by a validation step.
from itertools import compress
letters = "ABCDEF"
flags = [1, 0, 1, 0, 1, 1]
print(list(compress(letters, flags)))This prints ['A', 'C', 'E', 'F']. The result stops when either input runs out, so a short selector list silently truncates the output.
Common errors
- Losing the boundary item.
takewhilehas to read the first failing item to know it failed, and it discards that item. If you keep using the same iterator afterwards, that item is gone:
from itertools import takewhile
it = iter([1, 4, 6, 2])
print(list(takewhile(lambda x: x < 5, it)))
print(next(it))The output is [1, 4] and then 2. The 6 was consumed and thrown away. If you need it, keep the boundary item yourself or use tee.
- Expecting dropwhile to filter everywhere. It only removes a leading run. Use
filterfalseor a generator expression to filter the whole stream. - Using takewhile when you want all matches.
takewhilestops at the first failure even if later items would pass. Usefilterfor that. - Passing a one-shot iterator as the selectors argument and then reusing it. Both inputs to
compressare consumed.
Choosing between them
Use takewhile and dropwhile on data with a meaningful order, such as sorted values, log lines after a header, or a stream with a sentinel. Use filterfalse for item-by-item rejection. Use compress when the decision is already available as a parallel sequence of flags.
Exercise
Given values = [5, 2, 8, 1, 9], what do list(dropwhile(lambda x: x > 3, values)) and list(takewhile(lambda x: x > 3, values)) print?
Show answer
dropwhile prints [2, 8, 1, 9]. It drops the leading 5, then yields everything from the first failing item 2 onward, including 8 and 9. takewhile prints [5]. It stops at 2, the first item that fails the test.