Practical Examples
Real-World Collection Traversal Scenarios
Data Processing
## Processing student records
students = [
{'name': 'Alice', 'score': 85},
{'name': 'Bob', 'score': 92},
{'name': 'Charlie', 'score': 78}
]
## Calculate average score
total_score = sum(student['score'] for student in students)
average_score = total_score / len(students)
print(f"Class Average: {average_score}")
## Find top performers
top_students = [student for student in students if student['score'] > 80]
Nested Collection Handling
## Flattening nested lists
nested_list = [[1, 2], [3, 4], [5, 6]]
flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list) ## [1, 2, 3, 4, 5, 6]
Complex Filtering Operations
## Advanced filtering with multiple conditions
inventory = [
{'product': 'laptop', 'price': 1000, 'stock': 5},
{'product': 'phone', 'price': 500, 'stock': 10},
{'product': 'tablet', 'price': 300, 'stock': 3}
]
## Find affordable and available products
available_products = [
item for item in inventory
if item['price'] < 800 and item['stock'] > 4
]
Traversal Flow Visualization
graph TD
A[Collection Traversal] --> B[Input Data]
B --> C{Filtering}
C --> |Pass| D[Transformation]
C --> |Fail| E[Discard]
D --> F[Output Result]
Traversal Method |
Time Complexity |
Memory Usage |
Readability |
For Loop |
O(n) |
Medium |
High |
List Comprehension |
O(n) |
High |
Medium |
Generator |
O(n) |
Low |
Medium |
Advanced Traversal Patterns
## Combining multiple traversal techniques
def process_data(data):
## Chained operations
result = (
data
| filter(lambda x: x > 10)
| map(lambda x: x * 2)
| list
)
return result
numbers = [5, 15, 25, 8, 12]
processed = process_data(numbers)
print(processed) ## [30, 50]
Error Handling in Traversal
## Safe traversal with exception handling
def safe_traverse(collection, transform_func):
try:
return [transform_func(item) for item in collection]
except Exception as e:
print(f"Traversal error: {e}")
return []
## Example usage
safe_traverse([1, 2, '3'], int)
Best Practices for Efficient Traversal
- Choose the right collection type
- Use appropriate traversal method
- Consider memory and performance
- Handle potential errors gracefully
At LabEx, we recommend mastering these practical traversal techniques to write more robust and efficient Python code.