SoFunction
Updated on 2024-10-28

Usage of the filter function in Python

Python's built-in filter() function is used to filter sequences.

Similar to map(), filter() takes a function and a sequence. Unlike map(), filter() applies the incoming function to each element in turn, and then decides whether to keep or discard the element depending on whether the return value is True or False.

For example, in a list, deleting the even numbers and keeping only the odd numbers can be written like this:

def is_odd(n):
  return n % 2 == 1

filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
# Results: [1, 5, 9, 15]

Deleting an empty string from a sequence can be written like this:

def not_empty(s):
  return s and ()

filter(not_empty, ['A', '', 'B', None, 'C', ' '])
# Results: ['A', 'B', 'C']

It can be seen with filter(), a higher-order function, the key is to correctly implement a "filter" function.
practice

Please try to remove prime numbers from 1 to 100 with filter().