Skip to main content
How to Filter a List in Python

How to Filter a List in Python

This tutorial help to filter list items based on condition. We’ll learn different ways to filter list items in python.

You can also checkout other python list tutorials:

Filter with List Comprehension

The most common way to filter python list items is list comprehension, We can create statement like [x for x in list if condition]. You can replace the condition with any function of x you would like to use as a filtering condition.

salary = [100, 102, 16, 90, 113, 401]
# Filter all elements <8
emps = [s for s in salary if s > 100]
print(emps)

Output:

[102, 113, 401]

Using filter() method

We can also filter list items using the built-in Python filter() function.

The Syntax of the filter() function:

filter(fn, list)

Where:

fn: The function that tests if each element of a sequence true or not.
list: The sequence which needs to be filtered, it can be lists, sets, tuples or containers of any iterators.

The filter() method loops through the list’s items, applying the fn() function to each one. It returns an iterator for the elements for which fn() is True.

def filter_age(age):
    if (age >40):
        return True
    else:
        return False
  
ages = [20, 33, 44, 66, 78]
filtered = filter(filter_age, ages)

print('The filtered ages are:')
for a in filtered:
    print(a)

Output:

The filtered ages are:
44
66
78

Python Filter List with Regex

The re.match() also used to filter string lists.The re.match() method that returns a match object if there’s a match or None otherwise.

import re
# Define the list and the regex pattern to match
emps = ['Adam', 'Rachel', 'Joe', 'Alam']
pattern = 'A.*'
# Filter out all elements that match the above pattern
filtered = [x for x in emps if re.match(pattern, x)]
print(filtered)

Output:

['Adam', 'Alam']

Python Filter List Using Lambda

The lambda function is used to separate list, tuple, or sets based on condition.

ages = [20, 33, 44, 66, 78]
filtered = filter (lambda a: a > 40, ages)
print(list(filtered))

Output:

[44, 66, 78]

Leave a Reply

Your email address will not be published. Required fields are marked *