A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/python/python_itertools_compress_function.htm below:

Python itertools.compress() Function

Python itertools.compress() Function

The Python itertools.compress() function is used to filter elements from an iterable based on a corresponding selector iterable. It returns only those elements for which the corresponding value in the selector is True.

This function is useful when you need to selectively extract elements from an iterable based on predefined conditions.

Syntax

Following is the syntax of the Python itertools.compress() function −

itertools.compress(data, selectors)
Parameters

This function accepts the following parameters −

Return Value

This function returns an iterator that produces elements from data where the corresponding value in selectors is True.

Example 1

Following is an example of the Python itertools.compress() function. Here, we filter a list of numbers based on a binary selector list −

import itertools

data = [1, 2, 3, 4, 5]
selectors = [1, 0, 1, 0, 1]  # 1 means include, 0 means exclude
filtered = itertools.compress(data, selectors)
for item in filtered:
   print(item)

Following is the output of the above code −

1
3
5
Example 2

Here, we use itertools.compress() function to filter a list of names based on a condition −

import itertools

names = ["Alice", "Bob", "Charlie", "David", "Eve"]
selectors = [True, False, True, False, True]  # Only True values are included
filtered_names = itertools.compress(names, selectors)
for name in filtered_names:
   print(name)

Output of the above code is as follows −

Alice
Charlie
Eve
Example 3

Now, we generate the selectors dynamically using a condition. In this example, we filter numbers that are greater than 10 −

import itertools

data = [5, 12, 7, 20, 8, 15]
selectors = [x > 10 for x in data]  # Generates [False, True, False, True, False, True]
filtered_data = itertools.compress(data, selectors)
for num in filtered_data:
   print(num)

The result obtained is as shown below −

12
20
15
Example 4

We can use itertools.compress() function with a mixed data type list to filter elements based on a custom condition. Here, we filter elements that are strings −

import itertools

data = ["apple", 42, "banana", 100, "cherry"]
selectors = [isinstance(x, str) for x in data]  # Checks if each element is a string
filtered_items = itertools.compress(data, selectors)
for item in filtered_items:
   print(item)

The result produced is as follows −

apple
banana
cherry

python_modules.htm


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4