Practical Examples
Data Processing Scenarios
Financial Calculations
## Calculate tax-adjusted incomes
incomes = [50000, 75000, 100000, 125000]
tax_rates = [0.2, 0.25, 0.3, 0.35]
after_tax_incomes = [
income * (1 - rate)
for income, rate in zip(incomes, tax_rates)
]
print(after_tax_incomes)
## Output: [40000.0, 56250.0, 70000.0, 81250.0]
## Transform temperature data
celsius_temps = [0, 10, 20, 30, 40]
fahrenheit_temps = [
round((temp * 9/5) + 32, 1)
for temp in celsius_temps
]
print(fahrenheit_temps)
## Output: [32.0, 50.0, 68.0, 86.0, 104.0]
Scientific Computing
Statistical Calculations
## Generate statistical insights
data = [12, 15, 18, 22, 25, 30]
squared_deviations = [
(x - sum(data)/len(data))**2
for x in data
]
variance = sum(squared_deviations) / len(data)
print(f"Variance: {variance}")
graph TD
A[Raw Data] --> B{Filter Condition}
B --> |Pass| C[Transform Data]
B --> |Reject| D[Discard]
C --> E[Result Set]
Complex Data Manipulation
## Advanced data processing
students = [
{'name': 'Alice', 'grades': [85, 90, 92]},
{'name': 'Bob', 'grades': [75, 80, 85]},
{'name': 'Charlie', 'grades': [90, 95, 98]}
]
high_performers = [
student['name']
for student in students
if sum(student['grades']) / len(student['grades']) > 85
]
print(high_performers)
## Output: ['Alice', 'Charlie']
Scenario |
Comprehension |
Traditional Loop |
Efficiency |
Simple Calculation |
Faster |
Slower |
High |
Complex Filtering |
Comparable |
Comparable |
Medium |
Large Data Sets |
Memory Efficient |
Less Efficient |
High |
Machine Learning Preprocessing
## Normalize numerical features
raw_features = [10, 20, 30, 40, 50]
max_value = max(raw_features)
normalized_features = [
feature / max_value
for feature in raw_features
]
print(normalized_features)
## Output: [0.2, 0.4, 0.6, 0.8, 1.0]
Error Handling and Validation
## Safe calculation with error handling
def safe_divide(numbers, divisor):
return [
num / divisor if divisor != 0 else 0
for num in numbers
]
data = [10, 20, 30, 40]
result = safe_divide(data, 2)
print(result)
## Output: [5.0, 10.0, 15.0, 20.0]
Best Practices
- Use comprehensions for clear, concise transformations
- Avoid complex logic within comprehensions
- Prioritize readability and performance
LabEx recommends practicing these practical examples to enhance your Python comprehension skills.