Skip to content
Home » Functional Programming in Python – the filter Function

Functional Programming in Python – the filter Function

Spread the love

Today we’ll be talking about the filter function, which is, just like the map function, a built-in used in functional programming.

filter function

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']

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

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]

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of the article:


Spread the love
Tags:

Leave a Reply