Conditional Logic Methods
Understanding Conditional Logic in Filtering
Conditional logic is the core mechanism that determines how elements are selected or rejected during filtering operations. Python offers multiple methods to implement sophisticated filtering strategies.
Primary Conditional Logic Techniques
1. Comparison Operators
## Basic comparison filtering
numbers = [10, 15, 20, 25, 30, 35, 40]
filtered_numbers = [num for num in numbers if num > 25]
print(filtered_numbers) ## Output: [30, 35, 40]
2. Logical Operators
## Complex condition using AND/OR
data = [
{'name': 'Alice', 'age': 25, 'city': 'New York'},
{'name': 'Bob', 'age': 30, 'city': 'San Francisco'},
{'name': 'Charlie', 'age': 22, 'city': 'New York'}
]
filtered_data = [
person for person in data
if person['age'] > 24 and person['city'] == 'New York'
]
Conditional Logic Operators
Operator |
Description |
Example |
== |
Equal to |
x == y |
!= |
Not equal to |
x != y |
> |
Greater than |
x > y |
< |
Less than |
x < y |
and |
Logical AND |
x > 0 and x < 10 |
or |
Logical OR |
x < 0 or x > 10 |
Advanced Filtering Strategies
flowchart TD
A[Input Data] --> B{Condition 1}
B --> |True| C{Condition 2}
B --> |False| D[Reject]
C --> |True| E[Accept]
C --> |False| D
Lambda Functions for Complex Filtering
## Using lambda for advanced filtering
products = [
{'name': 'Laptop', 'price': 1000, 'stock': 5},
{'name': 'Phone', 'price': 500, 'stock': 10},
{'name': 'Tablet', 'price': 300, 'stock': 2}
]
## Filter products with complex conditions
filtered_products = list(filter(
lambda p: p['price'] < 800 and p['stock'] > 3,
products
))
Conditional Filtering Patterns
1. Nested Conditions
## Nested condition filtering
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = [
num for num in data
if num > 3 and (num % 2 == 0 or num % 3 == 0)
]
print(result) ## Output: [4, 6, 8, 10]
## Conditional mapping and filtering
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
transformed = [
x * 2 if x % 2 == 0 else x
for x in numbers
if x > 5
]
print(transformed) ## Output: [6, 12, 10, 16, 14, 20]
Key Takeaways
- Conditional logic enables precise data filtering
- Multiple operators and techniques are available
- Choose the most readable and efficient method
At LabEx, we encourage exploring these conditional logic methods to enhance your Python programming skills.