for Loops
Repeat once for each item
In this lesson
Explain it like I’m 5
‘For each thing in this pile, do something with it.’ Python hands you the items one at a time so you can deal with each one.
Looping over a collection
The pattern is for item in collection:. On each pass, the loop variable (here item) is automatically set to the next element. You can loop over lists, strings (character by character), dictionaries, and more, anything Python calls iterable.
fruits = ["apple", "pear", "kiwi"]
for fruit in fruits:
print("I like", fruit)
I like apple I like pear I like kiwi
Counting with range()
When you want to repeat a fixed number of times, use range(). range(5) produces 0, 1, 2, 3, 4 (it starts at 0 and stops before the end). range(1, 6) gives 1–5, and range(0, 10, 2) counts by twos. range is the idiomatic way to say ‘do this N times’.
total = 0
for n in range(1, 6):
total = total + n
print("Sum 1..5 is", total)
Sum 1..5 is 15
Write a loop that prints the 3-times table from 3×1 to 3×10. Run it and check the last line is 3 x 10 = 30.
for n in range(1, 11):
print("3 x", n, "=", 3 * n)
To reach 10, your range must stop at 11: range(1, 11).
for n in range(1, 11):
print("3 x", n, "=", 3 * n)
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
Knowing the position with enumerate()
Sometimes you need both the item and its index. Rather than managing a counter by hand, wrap the collection in enumerate(): for index, item in enumerate(names): gives you both each pass. It’s cleaner and less error-prone than tracking the index yourself.
fruits = ["apple", "pear", "kiwi"]
for index, fruit in enumerate(fruits):
print(index, fruit)
0 apple 1 pear 2 kiwi
Nested loops
A loop can contain another loop. For every pass of the outer loop, the inner loop runs completely. This is how you process grids, tables, or all pairs of things, but each level of nesting multiplies the work, so keep an eye on how many total iterations you’re creating.
for row in range(1, 3):
for col in range(1, 4):
print(row, col)
1 1 1 2 1 3 2 1 2 2 2 3
Looping over two lists with zip(), and reversed()
Two built-ins make for loops more expressive. zip(a, b) walks two (or more) lists in parallel, handing you one item from each on every pass, perfect when related data lives in separate lists. reversed(seq) walks a sequence back to front.
(When your goal is to transform a list into a new one rather than just visit it, a list comprehension is often cleaner — that has its own lesson.)
names = ["Ada", "Bo", "Cy"]
scores = [90, 75, 88]
for name, score in zip(names, scores):
print(name, "scored", score)
for n in reversed([1, 2, 3]):
print(n)
Ada scored 90 Bo scored 75 Cy scored 88 3 2 1
Common mistake: Off-by-one errors with range()
range excludes its stop value, so range(1, 5) gives 1–4, not 1–5. It’s easy to forget the end is not included.
Remember: to include N, write range(start, N + 1). When in doubt, print the range as a list to see exactly what it produces.
Common mistake: Modifying a list while looping over it
Adding or removing items from the same list you’re iterating confuses Python’s internal position tracker and skips or repeats items.
Loop over a copy (for x in items[:]:) or build a new list instead of changing the one you’re iterating.
What numbers does range(2, 7) produce?
range starts at the first value and stops before the second, so 7 is excluded.
Why use enumerate() in a for loop?
enumerate() hands you the index and the item together, so you don’t track a counter yourself.
Mini exercise (medium)
Given words = ["red", "green", "blue"], print each word with its position starting at 1, like 1: red.
Your turn. Fill in the code below and press Run to test it right here, nothing to install.
words = ["red", "green", "blue"]
lines = []
# TODO: build "1: red", "2: green", "3: blue" (number from 1)
for word in words:
lines.append(word)
print(lines)
Use enumerate(words, start=1) to begin counting at 1.
words = ["red", "green", "blue"]
lines = []
for i, word in enumerate(words, start=1):
lines.append(f"{i}: {word}")
print(lines)
assert lines == ["1: red", "2: green", "3: blue"], "each line should look like 1: red"
print("✓ Numbered!")