For Loops & Iteration
Iterate cleanly through collections of data like lists and strings using the Python For loop and the powerful range() function.
The For Loop
While while loops are based on conditions, for loops are designed specifically to iterate over a sequence (like a list, a string, or a range of numbers) item by item.
users = ["Alice", "Bob", "Charlie"]
for user in users:
print(f"Sending email to {user}...")It reads almost like English: "For every user in the users list, print this message."
Generating Numbers with range()
If you just want a loop to run exactly 10 times, you don't need to manually create a list of 10 numbers. Python's range() function does this dynamically.
# Prints 0 through 4
for i in range(5):
print(i)The range() function can take up to three arguments: range(start, stop, step).
# Prints 2, 4, 6, 8 (Starts at 2, stops before 10, steps by 2)
for even in range(2, 10, 2):
print(even)Tracking Position with enumerate()
A common mistake is trying to manually track an index counter variable. Python has an elegant solution called enumerate() which gives you both the index and the item automatically.
for index, user in enumerate(users):
print(f"User #{index}: {user}")