Filtering Techniques
List Comprehension Filtering
List comprehension provides a concise way to filter lists based on boolean conditions:
## Basic filtering
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) ## [2, 4, 6, 8, 10]
Filter Function
The filter()
function offers another powerful filtering method:
def is_positive(x):
return x > 0
numbers = [-1, 0, 1, 2, -3, 4]
positive_numbers = list(filter(is_positive, numbers))
print(positive_numbers) ## [1, 2, 4]
Boolean Filtering Techniques
Technique |
Description |
Example |
List Comprehension |
Inline filtering |
[x for x in list if condition] |
filter() function |
Functional filtering |
filter(function, iterable) |
Conditional Expressions |
Ternary-like filtering |
value if condition else alternative |
Advanced Filtering with Multiple Conditions
## Complex filtering
data = [
{'name': 'Alice', 'age': 25, 'active': True},
{'name': 'Bob', 'age': 30, 'active': False},
{'name': 'Charlie', 'age': 35, 'active': True}
]
## Filter active users over 30
filtered_users = [
user for user in data
if user['active'] and user['age'] > 30
]
print(filtered_users)
Filtering Flow Visualization
graph TD
A[Input Data] --> B{Apply Filter Condition}
B -->|Passes Condition| C[Keep Item]
B -->|Fails Condition| D[Discard Item]
C --> E[Filtered Result]
D --> E
Boolean Indexing with NumPy
import numpy as np
## NumPy boolean filtering
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
filtered_arr = arr[arr % 2 == 0]
print(filtered_arr) ## [2 4 6 8 10]
Filtering Method |
Time Complexity |
Readability |
List Comprehension |
O(n) |
High |
filter() |
O(n) |
Medium |
Numpy Boolean Indexing |
O(n) |
High |
Key Filtering Strategies
- Use list comprehension for simple, readable filtering
- Leverage
filter()
for functional programming approaches
- Consider NumPy for numerical data filtering
LabEx recommends mastering these techniques to write efficient and clean filtering code in Python.