Search⌘ K
AI Features

compress(), dropwhile() and filterfalse()

Understand how to apply the compress dropwhile and filterfalse functions from Python's itertools module to selectively filter and manipulate iterable data based on conditions, improving iteration control in your code.

compress(data, selectors)

The compress sub-module is useful for picking the first iterable values according to the second iterable Boolean values. This works by making the second iterable a list of Booleans (or ones and zeroes which amounts to the same thing). Here’s how it works:

Python 3.5
from itertools import compress
letters = 'ABCDEFG'
bools = [True, False, True, True, False]
print (list(compress(letters, bools)))
#['A', 'C', 'D']

In this example, we have a group of seven letters and a list of five bools. Then we pass them into the compress function. The compress function will go through each respective iterable and check the first against the second. If the second iterable is True, then the ...