search

What is the use of the "compress" function in Python?

In Python, the compress() function is part of the itertools module and is used to filter elements from an iterable based on corresponding values from a selector iterable. It returns an iterator that yields only the elements from the original iterable for which the corresponding selector value is truthy.

The compress() function takes two arguments:

  • data: The input iterable from which elements will be selected.
  • selectors: An iterable containing truthy and falsey values. The length of selectors should be the same as or shorter than the length of data.

Here's an example to demonstrate the usage of the compress() function:

import itertools

my_list = ['A', 'B', 'C', 'D', 'E']
selectors = [True, False, True, False, True]

compressed_iterator = itertools.compress(my_list, selectors)

for item in compressed_iterator:
    print(item)

# Output: A C E

In this example, the compress() function filters the elements of my_list based on the corresponding values in selectors. The selectors list contains truthy and falsey values that determine which elements should be selected. Only the elements at positions where the corresponding selector value is truthy (True) are included in the output.

The compress() function effectively performs an element-wise filtering operation, where the truthiness of the selectors controls whether an element is included in the output or not.

It's important to note that the selectors iterable can be shorter than the data iterable. If the selectors iterable is exhausted before the data iterable, the compress() function stops producing elements.

The compress() function is useful when you need to filter elements from an iterable based on corresponding truthy values from another iterable. It allows you to selectively include or exclude elements from the original iterable, providing a flexible way to filter and process data based on specific conditions or criteria.

Related Questions You Might Be Interested