Saturday, September 6, 2025
HomeLanguagesPython – Itertools.compress()

Python – Itertools.compress()

Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.

Note: For more information, refer to Python Itertools

Compress()

The itertools.compress() falls under the category of terminating iterators. It means that these iterators are used to work on the short input sequences and produce the output based on the functionality of the method used.

Compress(): This iterator selectively picks the values to print from the passed container according to the boolean list value passed as other arguments. The arguments corresponding to boolean true are printed else all are skipped.

In this, we give two parameters to the function. The first parameter will the iterator and the second parameter will be a selector either True/1 or False/0. If the first parameter’s corresponding selector is True, then the corresponding data will be printed and we will get the output accordingly.

Syntax:

compress(iter, selector)

Example 1 :




# Python code to demonstrate the working of   
# compress() 
  
  
import itertools
import operator
  
  
Codes =['C', 'C++', 'Java', 'Python']
selectors = [False, False, False, True]
  
Best_Programming = itertools.compress(Codes, selectors)
  
for each in Best_Programming:
    print(each)


Output:

Python

In the above code, in the Codes list, we have stored four variables and in the selectors’ list, we have four boolean values. When we use the itertools.compress() then the value False is assigned to ‘C’, False to ‘C++’, False to ‘Java’ and True to ‘Python’. Now while iterating through the loop we will get the output to which the value True is assigned. So, we get only “Python” while iterating ‘Best Programming’.

Example 2 :




# Python code to demonstrate the working of   
# compress() 
  
  
  
import itertools
import operator
  
  
example = itertools.compress('ABCDE', [1, 0, 1, 0, 0])
  
for each in example:
    print(each)


Output:

A
C
RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS