Python – Filter Elements of a Set

To filter elements of a Set in Python, call filter() builtin function and pass the filtering function and set as arguments. The filtering function should take an argument and return True if the item has to be in the result, or False if the item has to be not in the result.

filter() function returns a filter object, which we can convert it to a set using set() builtin function.

Python filter() builtin function

Examples

ADVERTISEMENT

1. Filter Positive Numbers from a Set

In the following program, we take a set s with some numbers, and filter only positive numbers using filter function.

Python Program

s = {2, -5, -8, 1, -14, 3, 16}
result = filter(lambda x: x >= 0, s)
result = set(result)
print(result)
Try Online

Output

{16, 1, 2, 3}

2. Filter strings of length 5 in a set

Now, let us take a set of strings are filter those strings whose length is 5.

Python Program

s = {'Apple', 'Banana', 'Mango', 'Cherry'}
result = filter(lambda x: len(x) == 5, s)
result = set(result)
print(result)
Try Online

Output

{'Mango', 'Apple'}

Conclusion

In this Python Tutorial, we learned how to filter items of a Set in Python using filter() function, with examples.