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.
#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:
- Create your own ChatGPT with Python
- SQLite | CRUD Operations in Python
- Event Management System Project in Python
- Ticket Booking and Management in Python
- Hostel Management System Project in Python
- Sales Management System Project in Python
- Bank Management System Project in C++
- Python Download File from URL | 4 Methods
- Python Programming Examples | Fundamental Programs in Python
- Spell Checker in Python
- Portfolio Management System in Python
- Stickman Game in Python
- Contact Book project in Python
- Loan Management System Project in Python
- Cab Booking System in Python
- Brick Breaker Game in Python
- Tank game in Python
- GUI Piano in Python
- Ludo Game in Python
- Rock Paper Scissors Game in Python
- Snake and Ladder Game in Python
- Puzzle Game in Python
- Medical Store Management System Project in Python
- Creating Dino Game in Python
- Tic Tac Toe Game in Python
- Test Typing Speed using Python App
- Scientific Calculator in Python
- GUI To-Do List App in Python Tkinter
- Scientific Calculator in Python using Tkinter
- GUI Chat Application in Python Tkinter