Here we will see the different ways to filer a list in python.
How to filter a list in python?
We see it is very frequently, filtering a list with a specific condition(s), in python we can filter the list in a couple of ways. Let’s see them.
filter()
As the name itself suggest, the filter()
function filters a list on a given condition. The filter()
is a Python built-in function hence we don’t need to install the python package to use it.
filtering even numbers.
numbers = [1, 2, 3, 4, 5, 6, 7]
even_numbers = list(filter(lambda item: item % 2 == 0, numbers))
print(f"Even numbers: {even_numbers}")
In the above example, we have a list with some numbers, using filter()
function we get the even numbers out of it. The filter takes a lambda expression to filter the collection.
Basically the filter()
function returns the filter object, to make it iterable we converted the filter to a list.
Output:
Even numbers: [2, 4, 6]
filter using for loop:
We can also filter the list using for
loop, but while taking advantage of the pythonic way of writing the code, we can accommodate this task with a single lined for loop.
even_numbers = [number for number in numbers if number % 2 == 0]
print(f"even numbers : {even_numbers}")
Output:
even numbers : [2, 4, 6]
References:
Happy Learning 🙂