Practical Examples
Real-World Scenarios
List comprehensions and summation techniques have numerous practical applications across various domains of programming.
Data Processing
Calculating Total Sales
sales_data = [
{'product': 'laptop', 'price': 1000},
{'product': 'phone', 'price': 500},
{'product': 'tablet', 'price': 300}
]
total_sales = sum([item['price'] for item in sales_data])
Scientific Computing
Statistical Calculations
## Calculate average temperature
temperatures = [22.5, 23.1, 21.8, 24.0, 22.9]
average_temp = sum(temperatures) / len(temperatures)
## Sum of temperatures above 23 degrees
high_temps_sum = sum([temp for temp in temperatures if temp > 23])
Text Processing
Word Length Analysis
words = ['python', 'programming', 'comprehension', 'example']
total_word_length = sum([len(word) for word in words])
Method |
Complexity |
Readability |
Performance |
Traditional Loop |
Medium |
Medium |
Slower |
List Comprehension |
Low |
High |
Faster |
Generator Expression |
Low |
High |
Most Efficient |
Filtering and Summing
## Sum of squared even numbers
numbers = range(1, 11)
squared_even_sum = sum([x**2 for x in numbers if x % 2 == 0])
Comprehension Workflow
graph TD
A[Input Data] --> B{Filter Condition}
B -->|Pass| C[Transform Data]
B -->|Fail| D[Discard]
C --> E[Aggregate/Sum]
E --> F[Result]
Advanced Example: Grade Analysis
students = [
{'name': 'Alice', 'grades': [85, 90, 92]},
{'name': 'Bob', 'grades': [75, 80, 85]},
{'name': 'Charlie', 'grades': [90, 95, 88]}
]
## Calculate total grades for students with average above 85
high_performers_total = sum([
sum(student['grades'])
for student in students
if sum(student['grades']) / len(student['grades']) > 85
])
Best Practices
- Use comprehensions for clear, concise code
- Prefer generator expressions for large datasets
- Keep transformations simple and readable
LabEx encourages developers to explore these powerful Python techniques to write more efficient and elegant code.