The itertools
module in the standard library provides a number of tools for conveniently iterating through a collection of elements.
The compress()
function in the module filters elements from an iterable using a Boolean selector.
compress(data, selectors)
data |
Required. A collection of elements in an iterable such as a list, tuple, set, etc. |
selectors |
A sequence of Boolean values( True /False ) which are in the same length as the iterable. If a selector has a value of True it indicates that the element in the corresponding index should be kept in the filtered output and False selectors indicate that the corresponding element should be discarded. |
The function returns an iterator which applies each boolean value in the selector to the corresponding element in the iterable and then yields only the elements that have a True
selector value.
from itertools import compress
data = ['PYTHON', 'java', 'C++', 'php', 'RUBY', 'SWIFT']
print('original: ', data)
selectors = list(map(lambda x: x.isupper(), data))
print('selectors: ', selectors)
compressed = list(compress(data, selectors))
print('compressed: ', compressed)
In the above example data
is a list containing strings.
We used the map function to create another list which is made up of the selectors in which each selector corresponds to a value in data, indicating whether all of its characters are uppercase.
We then used the compress function to filter those strings whose characters are not uppercase.
Its worth noting that the compress()
function does not actually create any elements in the memory until they are needed, making it memory-efficient.