Functions III

Introducing The Python Filter Function

In this tutorial, you'll learn how to filter iterables using the list method.


We've previously introduced map() as a built-in higher order function in Python.

Remember, a higher order function is a function that either accepts one or more functions as arguments, or returns a function as its result.

Now, let's talk about another built-in higher order function in Python: the filter() function.

The filter() function allows you to filter out elements from an iterable (like a list or a tuple) based on a certain condition.

The filter() function takes in two arguments: a function and an iterable. It applies the function to all elements of the iterable, and returns only those elements for which the function returns True.

Python

Here's a simple example of how to use the filter() function:

Python
Output

In this example, we're using the filter() function to filter out all numbers that are not greater than 3.

Just like with the map() function, the filter() function returns a filter object, which is an iterator. To get a list of results, we need to convert the filter object to a list using the list() function.

Python

What will be the output?

Python

What will be the output?

Python

Just like with the map() function, we can use lambda functions with the filter() function. This can make our code more concise.

Here's how we can rewrite our previous example using a lambda function:

Python
Output

What will be the output?

Python

What will be the output?

Python