SEMI-ADVANCED ENUMERATE EXAMPLES
Python
#!/usr/bin/env python3
"""
SEMI-ADVANCED ENUMERATE EXAMPLES
Complex patterns and combinations with other techniques
"""
print("=" * 60)
print("SEMI-ADVANCED ENUMERATE - Advanced Patterns")
print("=" * 60)
# Example 1: Enumerate with nested structures
print("\n1. Enumerating Nested Lists (Matrix/Table)")
print("-" * 40)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print("Matrix with row and column indices:")
for row_idx, row in enumerate(matrix):
for col_idx, value in enumerate(row):
print(f" Position [{row_idx}][{col_idx}] = {value}")
print("\nFormatted as table:")
for row_idx, row in enumerate(matrix):
row_str = " ".join(f"{val:3d}" for val in row)
print(f"Row {row_idx}: {row_str}")
# Example 2: Enumerate with zip for parallel iteration
print("\n2. Combining enumerate() with zip()")
print("-" * 40)
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["NYC", "LA", "Chicago"]
print("Processing multiple lists together:")
for index, (name, age, city) in enumerate(zip(names, ages, cities), start=1):
print(f"{index}. {name} (age {age}) lives in {city}")
# Example 3: Enumerate with list comprehension
print("\n3. Enumerate in List Comprehensions")
print("-" * 40)
words = ["hello", "world", "python", "code"]
# Create list of tuples with word length and position
word_info = [(idx, word, len(word)) for idx, word in enumerate(words)]
print(f"Words: {words}")
print("Word information (index, word, length):")
for info in word_info:
print(f" {info}")
# Filter based on index
even_position_words = [word for idx, word in enumerate(words) if idx % 2 == 0]
print(f"\nWords at even positions: {even_position_words}")
# Example 4: Enumerate with dictionary iteration
print("\n4. Enumerating Dictionary Items")
print("-" * 40)
student_grades = {
"Alice": 95,
"Bob": 87,
"Charlie": 92,
"Diana": 88
}
print("Student rankings by grade:")
# Sort by grade descending, then enumerate
sorted_students = sorted(student_grades.items(), key=lambda x: x[1], reverse=True)
for rank, (name, grade) in enumerate(sorted_students, start=1):
medal = "Gold" if rank == 1 else "Silver" if rank == 2 else "Bronze" if rank == 3 else ""
print(f" Rank {rank}: {name} - {grade}% {medal}")
# Example 5: Enumerate for state tracking in loops
print("\n5. State Machine with Enumerate")
print("-" * 40)
instructions = ["START", "LOAD", "PROCESS", "SAVE", "END"]
states = []
for step, instruction in enumerate(instructions):
state = {
'step': step,
'instruction': instruction,
'status': 'completed' if step < len(instructions) - 1 else 'current'
}
states.append(state)
prefix = ">" if step == len(instructions) - 1 else " "
print(f"{prefix} Step {step}: {instruction} [{state['status']}]")
# Example 6: Enumerate with conditional accumulation
print("\n6. Conditional Data Collection by Index")
print("-" * 40)
measurements = [45, 52, 48, 67, 71, 55, 49, 73, 68, 51]
print(f"Measurements: {measurements}")
# Collect every 3rd measurement starting from index 0
sampled = [(idx, val) for idx, val in enumerate(measurements) if idx % 3 == 0]
print(f"Sampled (every 3rd): {sampled}")
# Split into first half and second half with indices
midpoint = len(measurements) // 2
first_half = {idx: val for idx, val in enumerate(measurements) if idx < midpoint}
second_half = {idx: val for idx, val in enumerate(measurements) if idx >= midpoint}
print(f"First half (indices): {first_half}")
print(f"Second half (indices): {second_half}")
# Example 7: Enumerate with nested loops and tracking
print("\n7. Multi-level Enumeration with Combined Index")
print("-" * 40)
departments = {
"Engineering": ["Alice", "Bob"],
"Marketing": ["Charlie", "Diana", "Eve"],
"Sales": ["Frank"]
}
global_index = 0
for dept_idx, (dept_name, employees) in enumerate(departments.items()):
print(f"\nDepartment {dept_idx + 1}: {dept_name}")
for emp_idx, employee in enumerate(employees):
global_index += 1
print(f" {global_index}. {employee} (dept {dept_idx + 1}, local {emp_idx + 1})")
# Example 8: Enumerate for sliding window with index
print("\n8. Sliding Window with Position Tracking")
print("-" * 40)
data = [10, 20, 30, 40, 50, 60]
window_size = 3
print(f"Data: {data}, Window size: {window_size}")
for index in range(len(data) - window_size + 1):
window = data[index:index + window_size]
window_sum = sum(window)
print(f" Window at index {index}: {window} -> sum = {window_sum}")
# Example 9: Enumerate with generator expression
print("\n9. Memory-Efficient Enumeration (Generator)")
print("-" * 40)
def process_large_dataset():
"""Simulate large dataset processing"""
large_data = range(1, 21) # Simulating 1-20
# Generator expression with enumerate (memory efficient)
squared_with_index = ((idx, val**2) for idx, val in enumerate(large_data))
# Process only items at positions divisible by 5
for idx, squared in squared_with_index:
if idx % 5 == 0:
print(f" Index {idx}: {squared}")
print("Processing large dataset (showing every 5th item):")
process_large_dataset()
# Example 10: Enumerate for error tracking and recovery
print("\n10. Error Handling with Position Tracking")
print("-" * 40)
inputs = ["10", "20", "abc", "30", "def", "40"]
results = []
errors = []
for index, value in enumerate(inputs):
try:
result = int(value) * 2
results.append((index, result))
print(f" Position {index}: '{value}' -> {result}")
except ValueError:
errors.append((index, value))
print(f" Position {index}: '{value}' -> ERROR (invalid)")
print(f"\nSuccessful conversions: {len(results)}")
print(f"Errors at positions: {[idx for idx, _ in errors]}")
print(f"Error values: {[val for _, val in errors]}")
print("\n" + "=" * 60)
print("Advanced Patterns:")
print(" - Nested enumerate for multi-dimensional data")
print(" - Combine with zip(), sorted(), filter()")
print(" - Use in comprehensions and generators")
print(" - Track state across complex iterations")
print(" - Error handling with position context")
print("=" * 60)