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
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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
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.
Example 1 :
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 :