To remove items from a set based on a condition in Python, you can use a set comprehension or the filter function along with a lambda expression.
In this example,
number_set
containing integer values {1, 2, 3, 4, 5}
.x % 2 != 0
checks if the number is odd.number_set
and includes it in the new set only if the condition is true.filtered_set
to see the removed items.number_set = {1, 2, 3, 4, 5}
filtered_set = {x for x in number_set if x % 2 != 0}
print(filtered_set)
{1, 3, 5}
In this example,
string_set
containing string values {'apple', 'banana', 'cherry', 'date', 'grape'}
.filter
function with a lambda expression to keep only the strings with a length greater than or equal to 6 characters. The lambda expression lambda x: len(x) >= 6
checks if the string length is at least 6.filter
function returns an iterator, so we convert it back to a set using the set
constructor.filtered_set
to see the removed items.string_set = {'apple', 'banana', 'cherry', 'date', 'grape'}
filtered_set = set(filter(lambda x: len(x) >= 6, string_set))
print(filtered_set)
{'banana', 'cherry'}
In this tutorial, we learned How to Remove Items from Set based on a Condition in Python language with well detailed examples.