Sub topic 6
Filtering streams with takewhile, dropwhile, filterfalse and compress
This chapter assumes you know the difference between an iterable and an iterator, that you can write a lambda predicate, and that you have seen islice and count from earlier chapters. The four tools here filter an iterator without building a list. Two of them decide by position in the stream (takewhile, dropwhile). One inverts the built-in filter (filterfalse). One filters with a separate stream of yes/no flags (compress).
The four filters at a glance
| Function | Keeps | Stops early? | Predicate or selector |
|---|---|---|---|
| `takewhile(pred, it)` | Items before the first one that fails `pred` | Yes, at the first failure | Predicate required |
| `dropwhile(pred, it)` | Everything from the first item that fails `pred` onward | No, it must read the whole input | Predicate required |
| `filterfalse(pred, it)` | Items for which `pred` is false | No | `None` tests truthiness |
| `compress(data, selectors)` | Items whose matching selector is truthy | When either input ends | A second iterable of flags |
All four return lazy iterators. Nothing is computed until you consume the result, and each one can be consumed only once.
takewhile: keep the head of a stream
takewhile(predicate, iterable) yields items while the predicate is true. At the first item where it is false, it stops permanently. It never looks at the rest of the input, even if later items would pass.
from itertools import takewhile
values = [1, 4, 6, 2]
print(list(takewhile(lambda x: x < 5, values)))This prints [1, 4]. The 2 at the end is below 5, but it comes after the failing 6, so it is never tested.
Because takewhile stops early, it can turn an infinite stream into a finite one. This is the main reason to prefer it over filter, which would run forever on an infinite source.
from itertools import count, takewhile
squares_under_50 = takewhile(lambda n: n * n < 50, count(1))
print(list(squares_under_50))This prints [1, 2, 3, 4, 5, 6, 7]. The stream stops when 8 * 8 = 64 fails the test.
You can see the laziness by giving the source a side effect:
from itertools import takewhile
def noisy(n):
for i in range(n):
print("produce", i)
yield i
print(list(takewhile(lambda x: x < 2, noisy(100))))The output is produce 0, produce 1, produce 2, then [0, 1]. The generator produced only three items out of 100. The third item, 2, was needed to discover that the condition had failed.
The item that ends takewhile is consumed
The failing item is read from the source and then discarded. If you keep using the same iterator afterwards, that item is gone.
from itertools import takewhile
it = iter([1, 2, 10, 3, 4])
print(list(takewhile(lambda x: x < 5, it)))
print(list(it))This prints [1, 2] and then [3, 4]. The 10 was pulled from it to test it and is not in either result. When you need to resume from the boundary, use a pattern that keeps that element, such as tee (covered in a later chapter) or a plain loop with break.
dropwhile: skip a leading run
dropwhile(predicate, iterable) is the mirror image. It discards items while the predicate is true. At the first false result it yields that item and then yields every remaining item without testing them again.
from itertools import dropwhile
values = [1, 4, 6, 2]
print(list(dropwhile(lambda x: x < 5, values)))This prints [6, 2]. The 2 is kept even though it satisfies x < 5, because dropping ended at 6.
The two functions split a stream at the same boundary. takewhile gives the part before it, and dropwhile gives the part from it onward. Together they cover every item exactly once, as long as the source is a sequence you can iterate twice.
takewhile has the same shape, with the roles reversed. It starts in a passing state and moves to a stopped state at the first false result.
Combining the two to cut a window
Chaining dropwhile and takewhile extracts a region between two markers. Here the first marker is skipped with islice.
from itertools import dropwhile, islice, takewhile
lines = ["noise", "START", "a", "b", "END", "tail"]
after_start = dropwhile(lambda s: s != "START", lines)
body = takewhile(lambda s: s != "END", islice(after_start, 1, None))
print(list(body))This prints ['a', 'b']. The dropwhile step yields START, a, b, END, tail. The islice(..., 1, None) step drops the START line itself. The takewhile step stops at END. No intermediate list is created, so this works on a file object with millions of lines.
filterfalse: the opposite of filter
filterfalse(predicate, iterable) yields the items for which the predicate is false. It is the same as filter(lambda x: not predicate(x), iterable), but it reads better and avoids the extra function call.
from itertools import filterfalse
print(list(filterfalse(lambda x: x % 2, range(10))))This prints [0, 2, 4, 6, 8]. Odd numbers make x % 2 equal to 1, which is truthy, so they are rejected.
When the predicate is None, filterfalse tests each item's truthiness directly. This keeps the falsy items, which is the opposite of what filter(None, ...) does.
from itertools import filterfalse
mixed = [0, 1, "", "a", None, []]
print(list(filterfalse(None, mixed)))This prints [0, '', None, []].
Splitting a stream into two with filterfalse
A common use is a partition helper that sends items to two outputs. It needs tee so that both outputs can read the same source.
from itertools import filterfalse, tee
def partition(pred, iterable):
t1, t2 = tee(iterable)
return filterfalse(pred, t1), filter(pred, t2)
evens, odds = partition(lambda n: n % 2, range(10))
print(list(evens))
print(list(odds))This prints [0, 2, 4, 6, 8] and then [1, 3, 5, 7, 9]. The predicate runs once per item per branch, so avoid an expensive predicate here. If you consume one branch fully before the other, tee buffers every item in between. That cost is covered in the tee chapter.
compress: filter with a parallel stream of flags
compress(data, selectors) pairs each data item with a selector and yields the data item when its selector is truthy. The selectors are a separate iterable. They are not a function of the item.
from itertools import compress
print(list(compress("ABCDEF", [1, 0, 1, 0, 1, 1])))This prints ['A', 'C', 'E', 'F'].
This is useful when the decision comes from somewhere other than the item itself. In the next example, the selectors come from a different list.
from itertools import compress
names = ["ann", "bob", "cy", "dee"]
scores = [90, 55, 70, 40]
passed = compress(names, (s >= 60 for s in scores))
print(list(passed))This prints ['ann', 'cy']. Another case is picking columns from a row using a fixed mask:
from itertools import compress
keep = [True, False, True]
row = (7, "Ann", 31)
print(list(compress(row, keep)))This prints [7, 31]. You can reuse the same keep list for every row, which is clearer than repeating index lookups.
compress stops at the shorter input
compress stops as soon as either the data or the selectors run out. It does not raise an error and it does not pad.
from itertools import compress
print(list(compress("ABCD", [1, 1])))This prints ['A', 'B']. If your selectors are accidentally shorter than your data, you will silently lose the tail. When the lengths must match, check them first or use zip(..., strict=True) (Python 3.10+) in a comprehension instead.
Choosing between them
- Use
filteror a comprehension when each item is judged on its own and you want all matches. - Use
filterfalsewhen the rule is naturally written as the thing to reject. - Use
takewhilewhen the data is ordered or has a clear end condition, and you want to stop reading early. - Use
dropwhileto skip a header, a warm-up period, or leading padding. - Use
compresswhen the yes/no decisions already exist as a separate stream.
Common errors
- Expecting
dropwhileto remove all matches. It only removes the leading run. Later matching items stay. - Reusing an exhausted result. The value returned by any of these functions is an iterator. A second
list()call on it returns[]. - Losing the boundary item after
takewhile. The first failing item is consumed from the source. Do not count on finding it on the next read. - Predicates with side effects.
takewhileanddropwhilecall the predicate once per item and never again. A predicate that updates a counter or reads state will behave differently from what a rerun on a list suggests. - Mismatched lengths in
compress. The shorter input wins, with no warning. - Passing
Noneas the predicate totakewhileordropwhile. Onlyfilterfalse(andfilter) acceptNoneas shorthand for truthiness. For the other two, writeboolas the predicate.
Exercise
What does list(dropwhile(lambda x: x < 3, [1, 2, 5, 1, 2])) return, and why does the result still contain 1 and 2?
Show answer
It returns [5, 1, 2]. dropwhile discards only the leading run of items that satisfy the predicate (1 and 2). It yields 5, the first item that fails, and then passes every later item through without testing it, so the trailing 1 and 2 are kept.
Exercise
You have names = ["a", "b", "c", "d"] and flags = [True, False, True]. What does list(compress(names, flags)) give, and what happens to "d"?
Show answer
It gives ['a', 'c']. compress stops when the shorter input (flags) ends, so "d" is never examined and no error is raised.
Exercise
Write a lazy expression that yields the numbers from count(1) while their cube is below 200, using a single itertools function. What does it produce?
Show answer
takewhile(lambda n: n ** 3 < 200, count(1)). It produces 1, 2, 3, 4, 5, because 5 cubed is 125 and 6 cubed is 216, which fails the test and ends the stream.