Practical List Operations
Real-World Data Processing
Filtering Data
## Filter even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
## Filter complex conditions
students = [
{'name': 'Alice', 'grade': 85},
{'name': 'Bob', 'grade': 92},
{'name': 'Charlie', 'grade': 78}
]
high_performers = [student for student in students if student['grade'] > 80]
Mapping and Converting
## Convert temperatures
celsius = [0, 10, 20, 30, 40]
fahrenheit = [temp * 9/5 + 32 for temp in celsius]
## String manipulations
words = ['hello', 'world', 'python']
uppercase_words = [word.upper() for word in words]
List Aggregation Methods
## Numerical aggregations
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
average = sum(numbers) / len(numbers)
maximum = max(numbers)
minimum = min(numbers)
Complex List Operations
Nested List Processing
## Flatten nested lists
nested_list = [[1, 2], [3, 4], [5, 6]]
flattened = [item for sublist in nested_list for item in sublist]
Data Analysis Workflow
graph TD
A[Raw List] --> B[Filter]
B --> C[Transform]
C --> D[Aggregate]
D --> E[Analyze]
Operation |
Method |
Time Complexity |
Filtering |
List Comprehension |
O(n) |
Mapping |
List Comprehension |
O(n) |
Aggregation |
Built-in Functions |
O(n) |
Advanced List Techniques
Grouping and Counting
## Count occurrences
fruits = ['apple', 'banana', 'apple', 'cherry', 'banana']
from collections import Counter
fruit_counts = Counter(fruits)
Zip and Parallel Processing
## Combine multiple lists
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
combined = list(zip(names, ages))
Error Handling in List Operations
def safe_division(numbers):
try:
return [10 / num for num in numbers if num != 0]
except ZeroDivisionError:
return "Cannot divide by zero"
LabEx Best Practices
- Use list comprehensions for concise code
- Leverage built-in functions for efficiency
- Handle potential errors gracefully
- Choose appropriate data structures
By mastering these practical list operations, you'll be able to handle complex data manipulation tasks efficiently in Python, particularly in LabEx programming environments.