Practical Filter Examples
Real-World Filtering Scenarios
Filter functions are powerful tools for data manipulation across various domains. This section explores practical applications of filtering in Python.
Example 1: Filtering Numeric Data
## Filtering prime numbers
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
numbers = range(1, 50)
prime_numbers = list(filter(is_prime, numbers))
print(prime_numbers)
## Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Example 2: Filtering Strings
## Filtering words by length
words = ['python', 'java', 'javascript', 'c++', 'ruby', 'go']
long_words = list(filter(lambda word: len(word) > 4, words))
print(long_words)
## Output: ['python', 'javascript']
Example 3: Filtering Complex Objects
## Filtering students based on multiple criteria
class Student:
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
students = [
Student("Alice", 85, 20),
Student("Bob", 45, 22),
Student("Charlie", 92, 19),
Student("David", 60, 21)
]
## Filter students with grade > 80 and age < 21
top_young_students = list(filter(lambda s: s.grade > 80 and s.age < 21, students))
top_young_names = [s.name for s in top_young_students]
print(top_young_names)
## Output: ['Charlie']
Filtering Workflow
graph TD
A[Input Data] --> B{Filter Condition}
B -->|Matches Criteria| C[Keep Element]
B -->|Fails Criteria| D[Remove Element]
C --> E[Filtered Result]
D --> E
Scenario |
Recommended Approach |
Performance |
Small Lists |
filter() |
Excellent |
Large Lists |
List Comprehension |
Better |
Complex Conditions |
Custom Function |
Flexible |
Advanced Filtering Techniques
## Combining multiple filters
def is_even(x):
return x % 2 == 0
def is_less_than_50(x):
return x < 50
numbers = range(1, 100)
filtered_numbers = list(filter(lambda x: is_even(x) and is_less_than_50(x), numbers))
print(filtered_numbers)
## Output: [2, 4, 6, ..., 48]
Best Practices
- Use clear, concise filter conditions
- Prefer list comprehensions for simple filters
- Create reusable filter functions
- Consider performance with large datasets
By mastering these practical examples, you'll enhance your data processing skills with LabEx and write more efficient Python code.