🌱BeginnerControl Flow
for Loops
Iterating over sequences, ranges, and collections with Python's for loop.
Overview
The for loop in Python iterates over any iterable a sequence, collection, or generator executing the loop body for each item. Unlike C-style languages where you typically write a counter-based loop, Python's for loop works directly on the items themselves.
The built-in range() function generates a sequence of integers and is the standard way to run a loop a specific number of times. range(n) generates 0 through n-1; range(start, stop) generates start through stop-1; range(start, stop, step) lets you control the step size.
Two useful built-ins that pair with for loops: enumerate() gives you both the index and value, and zip() lets you iterate over two sequences in parallel. Both are commonly used in real Python code.
Key Points
- •for item in iterable: iterates over any sequence, list, string, tuple, dict, or range
- •range(n) generates 0 to n-1; range(5, 10) generates 5 to 9; range(0, 10, 2) generates even numbers
- •break exits the loop immediately; continue skips to the next iteration
- •enumerate(seq) yields (index, value) pairs avoids manual counter tracking
- •zip(a, b) iterates two sequences in parallel, pairing items by position
- •for loops can have an else clause it runs when the loop completes normally (not via break)
Examples
Iterating over a list and a string
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# apple
# banana
# cherry
for char in "Python":
print(char, end=" ") # P y t h o nrange() and enumerate()
# Count from 0 to 4
for i in range(5):
print(i, end=" ") # 0 1 2 3 4
# Count from 1 to 10, step 2
for i in range(1, 11, 2):
print(i, end=" ") # 1 3 5 7 9
# enumerate: index + value together
names = ["Alice", "Bob", "Carol"]
for i, name in enumerate(names):
print(f"{i}: {name}")
# 0: Alice 1: Bob 2: Carolbreak, continue, and zip()
# break exits the loop
for n in range(10):
if n == 5:
break
print(n, end=" ") # 0 1 2 3 4
# continue skips the current iteration
for n in range(10):
if n % 2 == 0:
continue
print(n, end=" ") # 1 3 5 7 9
# zip: iterate two lists in parallel
names = ["Alice", "Bob"]
scores = [95, 82]
for name, score in zip(names, scores):
print(f"{name}: {score}")Common Mistakes
- Modifying a list while iterating over it iterate over a copy: `for item in items[:]:`
- Using range(len(items)) when enumerate(items) is cleaner and more Pythonic
- Off-by-one errors: range(1, 10) gives 1–9, not 1–10; use range(1, 11) for 1–10
Note
If you find yourself writing `for i in range(len(my_list))` to access elements by index, switch to `for item in my_list` or `for i, item in enumerate(my_list)` it's cleaner and less error-prone.
Exercises
Write Python code to solve each exercise. Run it in your browser and check your output.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4