Advanced Techniques
Complex Iteration Strategies
1. Multi-Dimensional Enumeration
def multi_dimensional_enumerate(matrix):
return [
(row_idx, col_idx, value)
for row_idx, row in enumerate(matrix)
for col_idx, value in enumerate(row)
]
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
flattened = multi_dimensional_enumerate(grid)
print("Flattened Grid:", flattened)
Functional Programming Techniques
Enumerate with Lambda and Map
def transform_with_index(items):
return list(map(lambda x: x[0] * x[1], enumerate(items, 1)))
numbers = [10, 20, 30, 40]
weighted_numbers = transform_with_index(numbers)
print("Weighted Numbers:", weighted_numbers)
Advanced Filtering Techniques
graph TD
A[Advanced Filtering] --> B[Conditional Filtering]
A --> C[Complex Transformations]
A --> D[Nested Filtering]
Nested Filtering with Enumerate
def complex_filter(data):
return [
(index, item, len(str(item)))
for index, item in enumerate(data)
if (isinstance(item, (int, str)) and
(len(str(item)) > 3 or (isinstance(item, int) and item % 2 == 0)))
]
mixed_data = [2, 'long', 4, 'short', 6, 'very long', 8, [1, 2, 3]]
result = complex_filter(mixed_data)
print("Complex Filtered Result:", result)
Lazy Evaluation with Enumerate
def lazy_enumerate(iterable):
return (
(index, item)
for index, item in enumerate(iterable)
)
## Efficient for large datasets
large_list = range(1000000)
lazy_result = lazy_enumerate(large_list)
Custom Enumeration Techniques
Creating Custom Enumerators
class CustomEnumerator:
def __init__(self, iterable, start=0, step=1):
self.iterable = iterable
self.start = start
self.step = step
def __iter__(self):
for item in self.iterable:
yield (self.start, item)
self.start += self.step
custom_enum = CustomEnumerator(['a', 'b', 'c'], start=10, step=5)
print(list(custom_enum))
Comparative Analysis
Technique |
Complexity |
Memory Usage |
Use Case |
Standard Enumerate |
Low |
Efficient |
Simple iterations |
Lazy Enumerate |
Very Low |
Minimal |
Large datasets |
Custom Enumerator |
Medium |
Flexible |
Special indexing |
LabEx Advanced Patterns
- Combine enumerate with functional programming
- Use lazy evaluation for memory-intensive tasks
- Create custom enumeration strategies
Parallel Processing with Enumerate
from multiprocessing import Pool
def process_with_index(indexed_item):
index, item = indexed_item
return index * item
def parallel_process(items):
with Pool() as pool:
return pool.map(process_with_index, enumerate(items))
data = [1, 2, 3, 4, 5]
parallel_result = parallel_process(data)
print("Parallel Processed:", parallel_result)
Error Handling and Edge Cases
def robust_enumerate(iterable, default=None):
try:
return enumerate(iterable)
except TypeError:
return enumerate([default])