Select data items where a matching selector is truthy.
What You Will Learn
compress(data, selectors) pairs inputs positionally, stops when either iterator ends, and yields data where the corresponding selector evaluates as true.
Many iterator tools are lazy. Creating the iterator does not necessarily perform the work; advancing it can consume the original source.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from itertools import compress
print(list(compress(["A", "B", "C"], [1, 0, 1])))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: itertools.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression list(compress(['A', 'B', 'C'], [1, 0, 1])) prints ['A', 'C']. Compare that result with the rule above before you change the argument.
Expected output from the example:
['A', 'C']
Another Example: Compare the Results
Try a second input and compare it with the first. Notice whether the result changes in type, value, order, or number of items.
from itertools import compress
print(list(compress("ABCD", [1, 0, 1, 0])))
Expected output:
['A', 'C']
When You Would Use This
This pattern is useful in readers for CSV files, event streams, or paginated API results, where collecting everything in memory is unnecessary. Because iterator state advances when values are consumed, decide whether you need a reusable collection or a one-time pass. Keep files and connections open until their lazy consumers finish.
Practice: Modify the Code
Filter product names using a sequence of availability flags.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Expecting unmatched trailing elements to be retained if the selector sequence is shorter.
- Consuming a one-pass iterator during an earlier check and assuming the same values remain available.
Key Takeaways
- Select data items where a matching selector is truthy.
- compress(data, selectors) pairs inputs positionally, stops when either iterator ends, and yields data where the corresponding selector evaluates as true.
- Apply this operation only after checking the assumptions and input conditions shown in the example.