Practical Examples
Data Processing Scenarios
## Extract names starting with 'A'
names = ['Alice', 'Bob', 'Anna', 'Charlie', 'Andrew']
a_names = [name for name in names if name.startswith('A')]
print(a_names) ## Output: ['Alice', 'Anna', 'Andrew']
## Convert temperatures from Celsius to Fahrenheit
celsius_temps = [0, 10, 20, 30, 40]
fahrenheit_temps = [temp * 9/5 + 32 for temp in celsius_temps]
print(fahrenheit_temps) ## Output: [32.0, 50.0, 68.0, 86.0, 104.0]
Complex Filtering Workflows
graph TD
A[Raw Data] --> B{First Filter}
B --> |Pass| C{Second Filter}
C --> |Pass| D[Final Result]
B --> |Fail| E[Discarded]
C --> |Fail| E
3. Nested List Filtering
## Filter nested lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
even_numbers = [num for row in matrix for num in row if num % 2 == 0]
print(even_numbers) ## Output: [2, 4, 6, 8]
Real-world Application Examples
4. File Processing
## Filter log files
log_files = ['app.log', 'error.log', 'access.log', 'debug.log']
error_logs = [file for file in log_files if 'error' in file]
print(error_logs) ## Output: ['error.log']
5. Data Cleaning
## Remove empty strings and whitespace
raw_data = ['', 'Python', ' ', 'Programming', ' ']
cleaned_data = [item.strip() for item in raw_data if item.strip()]
print(cleaned_data) ## Output: ['Python', 'Programming']
Scenario |
Traditional Method |
List Comprehension |
Simple Filtering |
Slower |
Faster |
Complex Filtering |
More Lines |
Compact |
Readability |
Lower |
Higher |
6. Dictionary Comprehension
## Create dictionary from list
names = ['Alice', 'Bob', 'Charlie']
name_lengths = {name: len(name) for name in names}
print(name_lengths) ## Output: {'Alice': 5, 'Bob': 3, 'Charlie': 7}
Best Practices
- Use list comprehension for simple, clear transformations
- Avoid complex logic within comprehensions
- Prioritize readability
- Consider performance for large datasets
LabEx recommends mastering these techniques to write more efficient Python code.