Practical Use Cases
1. Numeric Data Processing
## 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]
2. String Manipulation
## Capitalize names and filter by length
names = ['alice', 'bob', 'charlie', 'david']
filtered_names = [name.capitalize() for name in names if len(name) > 4]
print(filtered_names)
## Output: ['Alice', 'Charlie', 'David']
Data Filtering Techniques
## Extract even-indexed elements from a list
original_list = ['a', 'b', 'c', 'd', 'e', 'f']
filtered_list = [item for index, item in enumerate(original_list) if index % 2 == 0]
print(filtered_list)
## Output: ['a', 'c', 'e']
4. Nested Data Processing
## Flatten a 2D list
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for sublist in nested_list for num in sublist]
print(flattened)
## Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Use Case Comparison
Scenario |
Traditional Method |
List Comprehension |
Data Filtering |
Multiple lines of code |
Concise single-line solution |
Transformation |
Explicit loops |
Compact and readable |
Performance |
Slower |
Generally faster |
Advanced Data Manipulation
## Convert dictionary to list of tuples
student_scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
high_scorers = [(name, score) for name, score in student_scores.items() if score > 80]
print(high_scorers)
## Output: [('Bob', 92)]
Workflow Visualization
graph TD
A[Input Data] --> B{Transformation Rule}
B -->|Apply| C[Filter Condition]
C -->|Pass| D[Add to Result]
C -->|Fail| E[Skip Item]
D --> F[Complete List]
6. Large Dataset Processing
## Generate prime numbers efficiently
def is_prime(n):
return n > 1 and all(n % i != 0 for i in range(2, int(n**0.5) + 1))
primes = [num for num in range(2, 100) if is_prime(num)]
print(primes)
Best Practices for Real-world Applications
- Use list comprehensions for simple transformations
- Avoid overly complex comprehensions
- Consider readability over brevity
- Use generator expressions for large datasets
LabEx recommends mastering these practical techniques to enhance your Python programming skills and write more efficient code.