itertools.compress Filters With Selector Flags
Filter parallel sequences with itertools.compress: pair data with boolean selectors, stop at the shorter input, and build selectors from predicates.
Code
from itertools import compress
def main() -> None:
names = ["alpha", "beta", "gamma", "delta", "epsilon"]
scores = [82, 47, 91, 65, 30]
passing = [score >= 60 for score in scores]
kept = list(compress(names, passing))
print("kept:", kept)
print("count:", len(kept))
# compress stops when either input is exhausted.
print("short selectors:", list(compress(names, [True, False])))
print("empty:", list(compress(names, [])))
# Selectors can be any iterable of truthy or falsy values.
flags = (1, 0, 1, 0, 1)
print("truthy flags:", list(compress(scores, flags)))
labels = ["new", "old", "new"]
predicate = (label == "new" for label in labels)
print("only new:", list(compress(names, predicate)))
if __name__ == "__main__":
main()Output
Captured from a sandboxed run of this snippet in the build pipeline.
kept: ['alpha', 'gamma', 'delta']
count: 3
short selectors: ['alpha']
empty: []
truthy flags: [82, 91, 30]
only new: ['alpha', 'gamma']What the code does
itertools.compress Filters With Selector Flags reduces to the function main.
What to watch for
- Self-contained — no imports beyond what the runtime already provides.
Applying it
Signature: def main() -> None
The demo output is labeled (kept:, count:, short selectors:), so every printed line maps back to its originating operation.
Interactive Tools for This Topic
CSS Specificity CalculatorCalculate CSS selector specificity scores using the standard (a, b, c) notation. Enter any selector and see its inline, ID, class, and element contributions instantly.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does itertools.compress Filters With Selector Flags print when run?
- Run it as a complete program — the output lines carry labels such as `kept:`, `count:`, `short selectors:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.