Today we’ll be talking about the filter function, which is, just like the map function, a built-in used in functional programming.
If you want to read my article on the map function, feel free to do it.
We use the filter function to select elements from a sequence for which a function returns True. We can use a function defined with the def statement as well as a lambda function.
If you want to learn more about lambda expressions and anonymous functions, I have an article about them, so feel free to read it.
Fine, time for an example.
Let’s use the filter function with a test function which returns True if an element starts with the letter ‘c’. This will filter out all the words that don’t start with this letter:
>>> words = ['cat', 'fish', 'dog', 'cow', 'pig', 'crow']
>>> list(filter(lambda word: word.startswith('c'), words))
['cat', 'cow', 'crow']
Just like maps, filters are iterables, so we have to convert them to lists if we want to see all the elements at once.
If you want to learn more about iterables and iterators, you can read this article.
And also just like with lists, we can achieve the same using a list comprehension instead of the filter function. Here’s how we would do it:
>>> [word for word in words if word.startswith('c')]
['cat', 'cow', 'crow']
And just one more example. This time we’ll define a function which returns True if the number passed as an argument is positive:
>>> def positive(num):
... return num > 0
...
Here’s our list of numbers:
>>> nums = [3, -6, -11, 2, 5]
And now, using the filter function with the positive function, let’s select just the positive numbers:
>>> list(filter(positive, nums))
[3, 2, 5]
Here’s the video version of the article: