On this page
itertools.compress
Prev: itertools.combinations_with_replacement | Up: itertools | Next: itertools.count
Rel: itertools.accumulate, itertools.batched, itertools.chain, itertools.combinations
Ref: docs.python.org — itertools.compress
Tags: #public #python3 #stdlib #itertools
Import
import itertools
from itertools import compress
Signature & Overview
itertools.compress(data, selectors)
Return data elements corresponding to true selector elements.
Usage
from itertools import compress
items = ["a", "b", "c", "d"]
mask = [1, 0, 1, 0]
assert list(compress(items, mask)) == ["a", "c"]
Gotchas
- Stops at the shorter iterable: If
selectorsis shorter thandata(or vice versa), remaining items are ignored without error. - Truthy/falsy selectors: Any truthy value selects the corresponding element—not just
True/False.
REPL Inspect
from itertools import compress
help(compress)
Linked from
Related notes
- tuts/python3/stdlib_module/itertools/combinations_with_replacement Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/count Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools/accumulate Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/batched Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/chain Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/combinations Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/cycle shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/dropwhile shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/filterfalse shared tags: #itertools, #stdlib