Streamline Your Python Code with Iterator Compression and Expansion

Transform Data Efficiently with These Handy Tools

Max N
3 min readApr 29, 2024
Photo by Arun Clarke on Unsplash

In Python, the itertools module offers a range of functions that can help you work more efficiently with iterables. Two particularly powerful functions are compress() and islice(), which allow you to compress and expand iterators, respectively. Let's explore how these functions work and see some practical examples.

Iterator Compression with compress()

The compress() function takes two iterables: a data iterable and a selector iterable. It returns an iterator that yields elements from the data iterable when the corresponding element in the selector iterable is truthy (evaluates to True).

from itertools import compress

data = [1, 2, 3, 4, 5]
selector = [True, False, True, True, False]

compressed_data = list(compress(data, selector))
print(compressed_data) # Output: [1, 3, 4]

In this example, the compress() function yields elements from the data list (1, 3, and 4) because their corresponding elements in the selector list are True.

The compress() function can be particularly useful when you need to filter elements based on a condition. Instead of using a list comprehension or a for loop with an if

--

--

Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.