Last modified: Oct 31, 2024 By Alexander Williams

Python Filter List: A Complete Guide

Filtering lists is a common Python operation that helps select specific items based on conditions.

This guide covers several ways to filter a list in Python with examples.

Using List Comprehension to Filter a List

List comprehensions provide a concise way to filter lists based on conditions.


numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)


[2, 4, 6]

In this example, even_numbers contains only the even numbers from numbers.

Using the filter() Function

The filter() function offers an efficient way to filter a list using a function and returns an iterator.

It’s often combined with lambda functions for inline conditions.


numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)


[2, 4, 6]

Here, filter() with lambda selects only even numbers, producing [2, 4, 6].

Using a Custom Function with filter()

You can also use a custom function in filter() for more complex filtering.

This approach is helpful when the filtering logic is too complex for a lambda function.


def is_even(num):
    return num % 2 == 0

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(is_even, numbers))
print(even_numbers)


[2, 4, 6]

Here, is_even() is used in filter() to filter even numbers.

Filtering List of Strings by Substring

You can filter strings in a list based on specific substrings using list comprehensions or filter().


words = ["apple", "banana", "cherry", "apricot"]
a_words = [word for word in words if "a" in word]
print(a_words)


['apple', 'banana', 'apricot']

In this case, a_words contains only words that include the letter "a".

Filtering Unique Items in a List

To filter unique items, set() can help by removing duplicates from the list.

This technique works especially well when order is not important.


numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers)


[1, 2, 3, 4, 5]

The use of set() removes duplicates and results in [1, 2, 3, 4, 5].

Conclusion

Filtering lists in Python can be done with list comprehensions, filter(), and set() for unique filtering.

Explore more on list operations in Adding a List to Another List in Python.

These methods make it easy to work with lists efficiently in Python.