To filter items of a set based on a condition in Python, you can use list comprehension or the filter function to create a new set from the filtered items.
In this example,
numberSet
using the curly braces syntax, which contains numeric values 1
, 5
, 10
, 15
, and 20
.set
constructor, resulting in a new set named filteredSet
.filteredSet
to see the filtered items.numberSet = {1, 5, 10, 15, 20}
filteredSet = {num for num in numberSet if num > 5}
print(filteredSet)
{10, 15, 20}
In this example,
stringSet
using the curly braces syntax, which contains string values 'apple'
, 'banana'
, 'cherry'
, 'date'
, and 'grape'
.set
constructor, resulting in a new set named filteredStringSet
.filteredStringSet
to see the filtered strings.stringSet = {'apple', 'banana', 'cherry', 'date', 'grape'}
filteredStringSet = {string for string in stringSet if 'a' in string}
print(filteredStringSet)
{'banana', 'apple', 'grape'}
In this tutorial, we learned How to Filter Items of a Set based on a Condition in Python language with well detailed examples.