How to Filter Lists in Python

To filter a list in Python, use the built-in filter() function.

For example, let’s filter a list of ages such that only the ages of 18+ are left:

ages = [4, 23, 32, 12, 88]

adult_ages = filter(lambda age: age >= 18, ages)
print(list(adult_ages))

Output:

[23, 32, 88]

Today you are going to learn three ways to filter a list in Python.

We start from a basic for loop approach. Then we use a list comprehension approach to make the code a bit more concise. Finally, we use the filter() function to make it even shorter.

How to Filter Python Lists—The Three Approahces

To filter a list in Python, you need to go through it element by element, apply a condition for each element, and save the ones that meet the criterion.

There are three approaches you can choose from:

  1. A for loop approach.
  2. A list comprehension.
  3. The built-in filter() function

Let’s go through each of these options.

1. For Loop Approach

The most straightforward and beginner-friendly approach to filtering a list is by using a for loop:

  • A for loop goes through each element of a list.
  • It checks if an element satisfies a condition.
  • Based on the condition it adds the element to the result.

For instance, let’s filter out ages less than 18:

ages = [4, 23, 32, 12, 88]

adult_ages = []

for age in ages:
    if age >= 18:
        adult_ages.append(age)

print(adult_ages)

Output:

[23, 32, 88]

2. List Comprehension Approach

If you are unfamiliar with comprehensions, feel free to check out this article.

In short, list comprehension is a shorthand for looping through a list with one line of code. It follows this syntax:

[element for element in elements if condition]

For example, let’s filter a list of ages using a list comprehension:

ages = [4, 23, 32, 12, 88]

adult_ages = [age for age in ages if age >= 18]

print(adult_ages)

Output:

[23, 32, 88]

This piece of code does the exact same thing as the for loop in the 1st chapter.

Now, let’s move on to the 3rd approach to filtering a list using the filter() function.

3. Filter Python Lists Using the Filter() Function

The syntax of using the filter() function in Python is:

filter(func, elements)

Where the filter() function applies a function called func for each element in a list called elements.

The filtering function is a condition that an element must satisfy. Otherwise, it will be dropped out from the result list.

The filter() function returns a filter object with the filtered elements. You can convert this filter object into a list using the list() function.

For example, let’s filter a list of ages such that only ages 18+ are left.

To do this, you need to first implement a filtering function that checks the ages. It can be a simple function that takes an age as its argument and checks it is 18+:

def age_check(age):
    return age >= 18

Now you can pass the age_check() function into the filter() function to filter a list of ages:

ages = [4, 23, 32, 12, 88]

adult_ages = filter(age_check, ages)
print(list(adult_ages))

Output:

[23, 32, 88]

This works such that:

  • The filter() function takes each age from the ages list and applies age_check() to it.
  • If an age passes the age_check() it will end up in the resulting list of filtered ages.

Now you understand how the filter() function works. It takes elements and filters them based on a criterion. The filtering criterion is a function applied for each element in the sequence. The result is a sequence that contains the values that met the criterion.

Filter() Function with Lambda Expressions

Next, let’s take it a step further by not implementing a separate filtering function. Instead, let’s implement the filtering functionality directly into the filter() function call as a lambda expression.

For example, let’s filter out ages less than 18 again:

ages = [4, 23, 32, 12, 88]

adult_ages = filter(lambda age: age >= 18, ages)
print(list(adult_ages))

To better understand how this piece of code works, you need to learn what lambda functions are.

What Are Lambda Functions in Python

In Python, lambda is a function that does not have a name. Lambda can take any number of arguments but only have a single expression.

Lambdas are useful when the functionality they provide is needed for a small period of time.

Lambdas follow this syntax:

lambda arguments : expression

For example, let’s create a regular function that takes two numbers and sums them up:

def sum(a, b):
    return a + b

Now you can call this function:

sum(10, 20) # returns 30

Next, let’s create a lambda function to do the exact same:

lambda a, b: a + b

This lambda function takes two arguments—the numbers a and b and sums them up. To return from lambda, the return keyword is not needed.

However, there is a problem with the lambda expression above. It does not have a name so there is no way for us to call it. If you want to call a lambda function, you need to do it right after defining it.

For example, to call the lambda that sums up two numbers:

(lambda a, b: a + b)(10, 20) # returns 30

Of course, summing up numbers this way is not clever as you could do 10 + 20 instead… But the point is to demonstrate how lambdas work.

In Python, lambda expressions are “one-time” functions you only need once. They are useful when you do not want to write a separate function for a task that you are going to perform only one time.

How to Filter Python Lists Using Lambdas

Now that you understand what a lambda expression is, let’s go back to the example of filtering a list of ages with a lambda function:

ages = [4, 23, 32, 12, 88]

adult_ages = filter(lambda age: age >= 18, ages)
print(list(adult_ages))

Instead of creating a separate age-checking function, you define a lambda expression lambda age: age >= 18. This lambda expression is only used once for filtering the list. Thus it would be a waste of code to write a separate age_check() function as it would never be used in the codebase again.

Conclusion

Today you learned how to filter a list in Python.

To filter elements in a sequence in Python, you need to loop through them and check if they pass a condition. There are three ways to do this:

  1. A for loop.
  2. A list comprehension.
  3. The built-in filter() function.

Thanks for reading. Happy filtering!

Further Reading