Practical Indexing Patterns
Filtering Elements with Indices
Selective Processing
numbers = [10, 15, 20, 25, 30, 35, 40]
filtered_numbers = [num for index, num in enumerate(numbers) if index % 2 == 0]
print(filtered_numbers) ## [10, 20, 30, 40]
Conditional Indexing
words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
long_words = [word for index, word in enumerate(words) if len(word) > 5]
print(long_words) ## ['banana', 'elderberry']
Parallel Iteration
Iterating Multiple Lists
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for index, (name, age) in enumerate(zip(names, ages)):
print(f"Person {index + 1}: {name} is {age} years old")
Creating Paired Dictionaries
keys = ['a', 'b', 'c']
values = [1, 2, 3]
paired_dict = {index: (key, value) for index, (key, value) in enumerate(zip(keys, values))}
print(paired_dict)
Advanced Slicing Techniques
Chunking Lists
def chunk_list(lst, chunk_size):
return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
chunks = chunk_list(data, 3)
print(chunks) ## [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
Sliding Window
def sliding_window(lst, window_size):
return [lst[i:i + window_size] for i in range(len(lst) - window_size + 1)]
sequence = [1, 2, 3, 4, 5]
windows = sliding_window(sequence, 3)
print(windows) ## [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
Error Handling and Validation
Safe Indexing
def safe_get(lst, index, default=None):
return lst[index] if 0 <= index < len(lst) else default
data = [10, 20, 30]
print(safe_get(data, 1)) ## 20
print(safe_get(data, 5)) ## None
print(safe_get(data, 5, 0)) ## 0
Efficient Searching
def find_all_indices(lst, target):
return [index for index, value in enumerate(lst) if value == target]
numbers = [1, 2, 3, 2, 4, 2, 5]
indices = find_all_indices(numbers, 2)
print(indices) ## [1, 3, 5]
Nested List Processing
nested_list = [[1, 2], [3, 4], [5, 6]]
flattened = [num for index, sublist in enumerate(nested_list)
for num in sublist if index % 2 == 0]
print(flattened) ## [1, 2, 5, 6]
Practical Workflow Pattern
Data Cleaning and Validation
def validate_data(data):
return {
index: item for index, item in enumerate(data)
if isinstance(item, (int, float)) and item > 0
}
raw_data = [1, -2, 'text', 3.14, None, 5]
clean_data = validate_data(raw_data)
print(clean_data) ## {0: 1, 3: 3.14, 5: 5}
Visualization of Indexing Patterns
flowchart TD
A[Input List] --> B{Enumerate}
B --> C[Index Tracking]
B --> D[Value Processing]
B --> E[Conditional Filtering]
C --> F[Parallel Iteration]
D --> G[Transformation]
E --> H[Selective Processing]
Key Takeaways
enumerate()
enables powerful indexing strategies
- Combine with list comprehensions for concise code
- Handle complex data processing efficiently
- Implement safe and flexible indexing techniques
By mastering these patterns, you'll write more sophisticated Python code with LabEx-level precision.