Boolean Filter Basics
What are Boolean Filters?
Boolean filters are conditional statements that evaluate data based on true or false conditions. In Python, these filters help developers selectively process or filter data by applying logical operations.
Key Concepts
Logical Operators
Python provides several logical operators for creating boolean filters:
Operator |
Description |
Example |
and |
Logical AND |
x > 0 and x < 10 |
or |
Logical OR |
x == 0 or x == 1 |
not |
Logical NOT |
not x > 5 |
Boolean Evaluation Flow
graph TD
A[Input Data] --> B{Boolean Condition}
B -->|True| C[Include/Process Data]
B -->|False| D[Exclude/Skip Data]
Basic Filter Examples
Simple List Filtering
## Filtering even numbers
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) ## Output: [2, 4, 6, 8, 10]
Complex Condition Filtering
## Filtering students above 18 and with good grades
students = [
{'name': 'Alice', 'age': 20, 'grade': 85},
{'name': 'Bob', 'age': 17, 'grade': 90},
{'name': 'Charlie', 'age': 19, 'grade': 75}
]
qualified_students = [
student for student in students
if student['age'] >= 18 and student['grade'] >= 80
]
print(qualified_students)
When working with large datasets, boolean filters can be computationally expensive. LabEx recommends using efficient filtering techniques like generator expressions or built-in filter functions.