Skip to content

ENUMERATE WITH LIST COMPREHENSION

Python
#!/usr/bin/env python3
"""
ENUMERATE WITH LIST COMPREHENSION
Build new lists with index tracking
"""

print("=== Add Index Prefix to Names ===")
names = ["Alice", "Bob", "Charlie", "David"]

# Create new list with numbered names
numbered_names = [f"{i}. {name}" for i, name in enumerate(names, start=1)]
print(numbered_names)

print("\n=== Filter Even-Indexed Items ===")
colors = ["red", "blue", "green", "yellow", "purple", "orange"]

# Keep only items at even indices (0, 2, 4...)
even_indexed = [color for i, color in enumerate(colors) if i % 2 == 0]
print(f"Even indices: {even_indexed}")

print("\n=== Create Dictionary from List ===")
fruits = ["apple", "banana", "cherry"]

# Map each fruit to its position
fruit_dict = {i: fruit for i, fruit in enumerate(fruits)}
print(f"Fruit dictionary: {fruit_dict}")

print("\n=== Uppercase Every Third Word ===")
words = ["one", "two", "three", "four", "five", "six", "seven", "eight"]

modified = [word.upper() if i % 3 == 0 else word for i, word in enumerate(words)]
print(f"Modified: {modified}")