Filter List in Python | 10 methods

Filter List in Python 10 methods

Filter List in Python is the process of selecting specific items from a list that meet certain criteria. This is a task that you will encounter every now and then if you are working with python. So here you will learn 10 different ways to filter List in Python.

1. Using for loop

We start by taking an empty list named filtered_list. Then we use a for loop to iterate over the entire list and with the help of an if-else statement we can filter all elements. Those elements which satisfy the condition inside the if statement gets appended in the filtered_list.

#filter the list containing only odd numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_list = []
for num in numbers:
    if num % 2 != 0:
        filtered_list.append(num)
print(filtered_list)

Output:

[1, 3, 5, 7, 9]

2. Using the filter function 

filter() is a built-in function in python which can be used to filter a list based on any condition that we provide. We will create a function called is_odd and pass this function with the list inside the filter function and store the result in a new list called filtered_list.

#filter the list containing only odd numbers
def is_odd(num):
    return num % 2 != 0

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_list = list(filter(is_odd, numbers))
print(filtered_list)

Output:

[1, 3, 5, 7, 9]

3. Using list comprehension

List comprehension provides a short syntax to create a new list based on the condition mentioned. We will use list comprehension with the condition to filter out all the odd elements and store the result in a new list called filtered_list.

list comprehension
#filter the list containing only odd numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_list = [x for x in numbers if x % 2 != 0]
print(filtered_list)

Output:

[1, 3, 5, 7, 9]

4. Using Nested List comprehension

We can also use nested list comprehension to apply more than one condition on filtering out the elements from a list.

#filter all the odd numbers which are divisible by 3
numbers = [1, 2, 3, 4, 12, 6, 15, 8, 9, 10]
filtered_list = [x for x in [x for x in numbers if x % 2 != 0] if x % 3 == 0]
print(filtered_list)

Output:

[3, 15, 9]

5. Using lambda with filter method

We will pass a lambda function and the list inside the filter function to filter the list and store it in a new list called filtered_list.

#filter all the odd numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_list = list(filter(lambda x: x % 2 != 0, numbers))
print(filtered_list)

Output:

[1, 3, 5, 7, 9]

6. Using map with lambda function

We can use the map with a lambda function to filter out all the odd elements from the list. First, we pass a lambda function and the list inside the map function. This map functions returns a filtered map object which is then converted into a list. Finally, we filter the odd elements from this list excluding -1.

#filter all the odd numbers
numbers = [13, 4, 5, 8, 5, 2, 9, 10]
odd_numbers = list(map(lambda x: x if x % 2 != 0 else -1, numbers))
filtered_list = [x for x in odd_numbers if x != -1]
print(filtered_list)

Output:

[13, 5, 5, 9]

7. Using itertools.compress method

itertools.compress is a function which is provided to us in the itertools module. The compress function takes two arguments, an iterable(in our case it is a list) and a selector which specifies which elements should be taken to create the filtered list.

#filter the odd elements
import itertools
numbers = [2, 1, 4, 5, 6, 9, 2, 3, 10, 11]
selector = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
filtered_list = list(itertools.compress(numbers, selector))
print(filtered_list)

Output:

[1, 5, 9, 3, 11]

8. Using functools.partial method

functools.partial is a function which is provided in the functools module. This can be useful in filtering lists, as we can use filter with functools.partial to only keep elements that satisfy certain conditions.

#filter the odd elements which are divisible by 3
from functools import partial

def is_odd(num, divisor):
    return num % divisor == 0

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
divisible_by_3 = partial(is_odd, divisor=3)
filtered_list = list(filter(divisible_by_3, numbers))
print(filtered_list)

Output:

[3, 6, 9]

9. Using regular expression pattern matching

We can use regular expression to match patterns and filter out the elements from a list. The code below filters a list of names based on whether they start with the letter ‘L’ using regular expressions. The re.match function is used to check each name in the name list against the pattern ‘L.*’. This pattern matches any string that starts with the letter ‘L’ and the filtered list is stored in the variable filtered_names.

#filter the names which start with L
import re

name = ["Luna", "Roma", "Rebel", "Leesa", "Natalia"]
pattern = "L.*"
filtered_names = [x for x in name if re.match(pattern, x)]

print(filtered_names)

Output:

['Luna', 'Leesa']

10. Using Pandas library

The code below filters a list of numbers with the help of pandas library to keep only odd numbers. The list is first converted into a data frame and then the filtering is performed by using boolean indexing on the data frame. The filtered list is obtained by selecting the column “numbers” from the data frame and then converting it back into a list using the tolist method.

#filter the odd numbers
import pandas as pd

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
df = pd.DataFrame(nums, columns=['nums'])
filtered_list = df[df['nums'] % 2 != 0]['nums'].tolist()
print(filtered_list)

Output:

[1, 3, 5, 7, 9]

Conclusion

This brings us to the end of this article where we learnt 10 different ways to filter List in Python. I have tried to explain every method briefly so that you can understand each of them.

Thank you for visiting our website.


Also Read:

Share:

Author: Puja Kumari