Skip to content

ENUMERATE WITH NESTED STRUCTURES

Python
#!/usr/bin/env python3
"""
ENUMERATE WITH NESTED STRUCTURES
Handle complex data structures with enumerate
"""

print("=== Enumerate 2D Lists (Matrix) ===")
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row_i, row in enumerate(matrix):
    for col_i, value in enumerate(row):
        print(f"[{row_i}][{col_i}] = {value}", end="  ")
    print()

print("\n=== Process List of Dictionaries ===")
students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 92},
    {"name": "Charlie", "score": 78}
]

for rank, student in enumerate(students, start=1):
    print(f"Rank {rank}: {student['name']} - Score: {student['score']}")

print("\n=== Flatten Nested List with Tracking ===")
nested = [[1, 2], [3, 4, 5], [6]]
flat = []

for outer_i, inner_list in enumerate(nested):
    for inner_i, value in enumerate(inner_list):
        flat.append((outer_i, inner_i, value))
        print(f"Outer[{outer_i}] Inner[{inner_i}] = {value}")

print(f"\nFlattened with positions: {flat}")

print("\n=== Enumerate Multiple Lists Together ===")
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["NYC", "LA", "Chicago"]

for i, (name, age, city) in enumerate(zip(names, ages, cities), start=1):
    print(f"{i}. {name}, {age} years old, lives in {city}")