Ways to Filter a List in Python
In Python, both the filter()
function and list comprehension can be used to filter a list. The choice between them depends on the specific scenario and personal preference. Here’s a comparison to help you make a decision.
The filter()
function:
- Pros: It provides an elegant solution to filter elements based on a given condition. It takes a function and an iterable as arguments, allowing for complex filtering logic.
- Cons: It requires defining a separate filtering function, which can add complexity to simple filtering tasks. It returns a filter object, which needs to be converted to a list using
list()
to obtain the desired result.
List comprehension:
- Pros: It offers a compact syntax for creating a new list based on a filtering condition. It doesn’t require defining a separate function and directly returns the filtered list.
- Cons: It may become less readable for complex filtering conditions involving multiple nested conditions or operations.
Now, it’s time for writing some code.
Examples
The following examples are arranged in order from basic to advanced.
Filtering a list of numbers (list comprehension)
This example uses list comprehension to produce a list of numbers that are equal to or greater than 50:
numbers = [49, 89, 57, 49, 40, 78, 73, 43, 81, 12]
numbers_greater_than_50 = [number for number in numbers if number > 50]
print(numbers_greater_than_50)
Output:
[89, 57, 78, 73, 81]
Filtering a list of strings (list comprehension)
This example uses list comprehension to filter words that start with P
:
words = ['Sling Academy', 'Turtle', 'Python', 'Programming']
filtered_words = [word for word in words if word.startswith('P')]
print(filtered_words)
Output:
['Python', 'Programming']
Filtering a list of dictionaries (with the filter() function)
In this example, we have a list of people. Each person is represented by a dictionary. Our goal is to get a list of people who are older than 99 by using the filter()
function.
users = [
{"name": "Demon of Hatred", "age": 98},
{"name": "Ranni the Witch", "age": 300},
{"name": "The Turtle", "age": 5000},
{"name": "Wolf", "age": 35},
]
# Filter users who are above the age of 99
filtered_users = list(filter(lambda user: user["age"] > 99, users))
print(filtered_users)
Output:
[
{'name': 'Ranni the Witch', 'age': 300},
{'name': 'The Turtle', 'age': 5000}
]
Filtering a list of class objects (with the filter() function)
In this example, we’ll use the filter()
function to retrieve products whose prices are greater than 2.0
from a list of given fiction products. The information of each product is stored in a class object with two attributes: name
and price
.
# Define Product class
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __repr__(self):
return f"Product(name='{self.name}', price={self.price})"
# Create a list of product instances
products = [
Product("Blade of Soul", 1.99),
Product("Sword of Flame", 0.99),
Product("Axe of Night", 2.49),
Product("Bow of Wind", 3.99),
]
# Filter products with price greater than $2.00
filtered_products = list(filter(lambda p: p.price > 2.00, products))
print(filtered_products)
Output:
[
Product(name='Axe of Night', price=2.49),
Product(name='Bow of Wind', price=3.99)
]
Conclusion
We’ve covered the Pythonic approaches to filtering a list in Python and walked through a few examples of applying them in practice. The tutorial ends here. Happy coding & have a nice day!