Practical Usage Examples
Data Filtering Scenarios
1. Numeric Data Filtering
## Filtering positive numbers
numbers = [-2, -1, 0, 1, 2, 3, 4, 5]
positive_numbers = list(filter(lambda x: x > 0, numbers))
print(positive_numbers) ## Output: [1, 2, 3, 4, 5]
2. String Filtering
## Filtering strings by length
words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
long_words = list(filter(lambda x: len(x) > 5, words))
print(long_words) ## Output: ['banana', 'elderberry']
Data Cleaning Techniques
Removing None and Empty Values
## Filtering out None and empty values
mixed_data = [1, None, 'hello', '', 0, [], 'world']
valid_data = list(filter(None, mixed_data))
print(valid_data) ## Output: [1, 'hello', 'world']
Complex Object Filtering
Filtering Objects with Specific Attributes
class Product:
def __init__(self, name, price, category):
self.name = name
self.price = price
self.category = category
products = [
Product('Laptop', 1000, 'Electronics'),
Product('Book', 20, 'Literature'),
Product('Smartphone', 500, 'Electronics'),
Product('Headphones', 150, 'Electronics')
]
## Filter electronics products
electronics = list(filter(lambda p: p.category == 'Electronics', products))
expensive_electronics = list(filter(lambda p: p.price > 500, electronics))
Combining Filter with Map
## Convert and filter numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_evens = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, numbers)))
print(squared_evens) ## Output: [4, 16, 36, 64, 100]
Filtering Workflow
graph LR
A[Raw Data] --> B{Filter Condition}
B -->|Pass| C[Filtered Data]
B -->|Fail| D[Discarded Data]
| Filtering Method |
Readability |
Performance |
Memory Efficiency |
| filter() |
Good |
Moderate |
Moderate |
| List Comprehension |
Excellent |
Fast |
Good |
| Generator Expression |
Excellent |
Lazy Evaluation |
Excellent |
Real-world Application Examples
- Log file analysis
- User data validation
- Financial transaction filtering
- Scientific data processing
Advanced Filtering Techniques
Multiple Condition Filtering
## Complex filtering with multiple conditions
def complex_filter(item):
return item > 10 and item % 2 == 0
numbers = [5, 12, 17, 20, 25, 30]
filtered_numbers = list(filter(complex_filter, numbers))
print(filtered_numbers) ## Output: [12, 20, 30]
By exploring these practical examples, you'll gain insights into filter functions with LabEx's comprehensive learning approach, enabling more efficient and elegant Python programming.