Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

itertools.compress

Yields data items paired with truthy selectors.

Version: Python 3.14; repository image, production runtime not attested

Syntax

itertools.compress(data, selectors)

Yields data items paired with truthy selectors.

Pairing stops when either iterable is exhausted, silently dropping an unmatched tail.

Pair successive items with selectors. A and C have true selectors, B has zero, and D lacks a partner when the selectors end. In the second call B passes but the last selector has no data partner. Iteration ends with the shorter input.

import itertools as I
assert list(I.compress("ABCD", [1, 0, 1])) == ["A", "C"]
assert list(I.compress("AB", [0, 1, 1])) == ["B"]

Examples

import itertools as I
print(list(I.compress("ABCD", [1, 0, 1])))
print(list(I.compress("AB", [0, 1, 1])))

Result

['A', 'C']
['B']

Pair successive items with selectors. A and C have true selectors, B has zero, and D lacks a partner when the selectors end. In the second call B passes but the last selector has no data partner. Iteration ends with the shorter input.

Sources