{"id":25577,"date":"2021-11-23T08:55:26","date_gmt":"2021-11-23T03:25:26","guid":{"rendered":"https:\/\/python-programs.com\/?p=25577"},"modified":"2021-11-23T08:55:26","modified_gmt":"2021-11-23T03:25:26","slug":"python-itertools-compress-function-with-examples","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-itertools-compress-function-with-examples\/","title":{"rendered":"Python Itertools.compress() Function with Examples"},"content":{"rendered":"

Itertools Module:<\/strong><\/p>\n

Itertools is a Python module that contains a collection of functions for dealing with iterators. They make it very simple to iterate through iterables such as lists and strings.<\/p>\n

Itertools.compress() Function:<\/strong><\/p>\n

Itertools.compress() belongs to the class of terminating iterators. This means that these iterators are used to process short input sequences and generate output based on the functionality of the method.<\/p>\n

This iterator selects the values to print from the passed container based on the boolean list value passed as an additional argument. If boolean true, the arguments are printed; otherwise, all are skipped.<\/p>\n

We give the function two parameters in this case. The first parameter is an iterator, and the second is a selector that can be True\/1 or False\/0. If the first parameter’s corresponding selector is True, the corresponding data will be printed, and the output will reflect this.<\/p>\n

 <\/p>\n

Syntax:<\/strong><\/p>\n

compress(iterator, selector)<\/pre>\n

Examples:<\/strong><\/p>\n

Example1:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given List = ['hello', 'this', 'is', 'btechgeeks']\r\nGiven selectors List = [True, False, False, True]<\/pre>\n

Output:<\/strong><\/p>\n

hello\r\nbtechgeeks<\/pre>\n

Explanation:<\/strong><\/p>\n

Here, In the selection list, first element is True. so, it prints the\r\nrespective index element from the given list 'hello'.\r\nIf it is False, respective index element from the given list gets skipped.\r\nTherefore it prints only 'hello' and 'btechgeeks' from given list.<\/pre>\n

Example2:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given String = \"hello\"\r\nGiven selectors List = [0, 1, 0, 1, 1]<\/pre>\n

Output:<\/strong><\/p>\n

e\r\nl\r\no<\/pre>\n

Itertools.compress() Function with Examples in Python<\/h2>\n