Looping Through Lists
Lists are sequences, making them perfect for for loops.
1. Simple Item Iteration (Preferred)
The easiest and most Pythonic way to loop through a list is to iterate over the items directly.
python zoo = ['lion', 'tiger', 'bear']
for animal in zoo: print(f"I saw a {animal} at the zoo.")
2. Item and Index Iteration (enumerate())
When you need both the item and its index (e.g., to create a numbered list or refer to the position), use the enumerate() function. It yields pairs of (index, item).
python names = ['Alice', 'Bob', 'Charlie']
print("--- Employee List ---") for index, name in enumerate(names): # enumerate starts counting from 0 by default print(f"{index + 1}. {name}")
Output:
--- Employee List ---
- Alice
- Bob
- Charlie