To filter a list in Python, the easiest way is with list comprehension.

lst = [0, 1, 2, 3, 4, 5]

filtered = [x for x in lst if x < 2]

print(filtered)

#Output:
[0, 1]

You can also use the Python filter() function with a lambda expression.

lst = [0, 1, 2, 3, 4, 5]

filtered = list(filter(lambda x: x < 2, lst))

print(filtered)

#Output:
[0, 1]

One other way to filter a list in Python is with a for loop.

lst = [0, 1, 2, 3, 4, 5]

filtered = []

for x in lst:
    if x < 2:
        filtered.append(x)

print(filtered)

#Output:
[0, 1]

When working with collections of data, the ability to modify and remove elements from your data based on conditions easily is valuable.

One such case is if you want to filter a list in Python.

Filtering lists is extremely common. There are a few ways you can filter a list in Python.

In our opinion, the easiest way to filter a list in Python is with list comprehension. The idea here is that you use list comprehension and if statement to filter items out of a list.

Below shows you how you can use list comprehension to filter a list in Python.

lst = [0, 1, 2, 3, 4, 5]

filtered = [x for x in lst if x < 2]

print(filtered)

#Output:
[0, 1]

How to Filter List with filter() Function in Python

Another way you can filter lists in Python is with the filter() function.

filter() allows you to filter iterable objects in Python with a lambda expression.

To use filter(), you pass a lambda expression and a list. Then filter() will return a filter object. Then, you convert the filter object to list with list().

Below shows you how to use filter() to filter a list in Python.

lst = [0, 1, 2, 3, 4, 5]

filtered = list(filter(lambda x: x < 2, lst))

print(filtered)

#Output:
[0, 1]

How to Filter List with for Loop in Python

One last way you can filter lists in Python is with a for loop.

Using loops to filter a list is the most basic way and can be more lines of code than if you used one of the examples above.

However, using a loop to filter a list in Python is valid and allows you more flexibility when adding items to the filtered list.

The process when using a for loop is that you first initialize an empty list and then you loop over each element. If a certain condition is met, you add the element to the empty list of filtered items.

Below shows you how to use a for loop to filter a list in Python.

lst = [0, 1, 2, 3, 4, 5]

filtered = []

for x in lst:
    if x < 2:
        filtered.append(x)

print(filtered)

#Output:
[0, 1]

Hopefully this article has been useful for you to learn how you can filter a list in Python.

Categorized in:

Python,

Last Update: March 11, 2024