for Loops and range
Loop over strings and lists with for, generate number sequences with range, build totals with accumulators, and choose between for and while.
Welcome back!
Step 1 of 12Learn
One pass per item
A for loop runs its block once for each item in a sequence:
for letter in "cat":
print(letter.upper())
# C
# A
# T
prices = [4.50, 12.00, 3.25]
for price in prices:
print(f"Item costs {price:.2f}")On each iteration, the loop variable (letter, price) is set to the next item, and the indented block runs. When the items run out, the loop ends. You never write a condition or an update, so a for loop over a finite collection can't run forever.
Choose loop variable names that describe one item: for price in prices, for name in names, for line in lines. Plural collection, singular item is a convention that makes loops read like sentences.
A for loop works on anything iterable: strings (character by character), lists, tuples, dictionaries (key by key), sets, files (line by line) and ranges of numbers. That consistency is one of Python's nicest features. Learn the for loop once and you can walk through almost any kind of data.
The loop variable keeps its last value after the loop ends. After the price loop above, price is 3.25. That's occasionally useful, but don't rely on it for anything important.
Step 2 of 12Learn
Counting with range()
To repeat something a fixed number of times, or loop over numbers, use range():
range(5)produces 0, 1, 2, 3, 4: five numbers, starting at 0, stopping before 5.range(1, 6)produces 1, 2, 3, 4, 5.range(0, 20, 5)produces 0, 5, 10, 15: the third argument is the step.range(10, 0, -2)counts down: 10, 8, 6, 4, 2.
for i in range(3):
print("Hip hip hooray!") # printed 3 times
for year in range(2026, 2031):
print(year) # 2026 through 2030The stop value is never included, just like slicing. This is the most common source of off-by-one errors: to count 1 to 10 you need range(1, 11). The rule that rescues you: range(a, b) contains exactly b - a numbers.
A range doesn't build a big list in memory; it produces numbers one at a time as the loop asks for them, so range(1_000_000) costs almost nothing. To see the numbers, wrap it in list(): list(range(1, 6)) shows [1, 2, 3, 4, 5].
If the step points away from the stop, such as range(5, 1) with the default step of 1, the range is empty and the loop body never runs. No error is raised, which can make this bug hard to spot.
Step 3 of 12Practice · Diagram
range(0, 10, 2) on a number line
Tap the last number range(0, 10, 2) actually produces.
Tap the shape that answers the question, then press Check.
- 0 (start)
0
- 2
2
- 4
4
- 6
6
- 8
8
- 10 (stop, not produced)
10
Step 4 of 12Try the calculator
range() inspector
Enter the three arguments of range(start, stop, step) with a positive step to see how many numbers it produces and which is last.
- How many numbers
- 6
- First number (if any)
- 2
- Last number (if any)
- 17
Step 5 of 12Practice · Fill in the blanks
Fill in the blanks
range(2, 10, 3) produces the numbers 2, 5 and . The stop value 10 is .
Step 6 of 12Learn
Accumulators: totals, counts and maximums
Most loops over data build up a result. The pattern is always the same: set up an accumulator before the loop, update it inside, use it after.
scores = [72, 95, 88, 61, 79]
total = 0
passed = 0
best = scores[0]
for score in scores:
total += score # running total
if score >= 70:
passed += 1 # counter with a condition
if score > best:
best = score # running maximum
average = total / len(scores)
print(total, passed, best, average) # 395 4 95 79.0Three mistakes show up constantly:
- Resetting inside the loop. If
total = 0is indented inside the loop, it resets on every pass, and the final total is just the last score. - Printing inside the loop when you meant to print once at the end, producing five partial totals.
- Starting a maximum at 0. If every value were negative,
best = 0would report 0 as the maximum. Start with the first item instead.
For simple cases Python has built-ins that do the looping for you: sum(scores), len(scores), max(scores) and min(scores). Use them when they fit; write the loop when you need something they can't do, like counting only passing scores.
Step 7 of 12Practice · Code challenge · Python
Complete count_passing(scores, pass_mark) so it returns how many scores in the list are greater than or equal to pass_mark. Use a for loop with a counter.
count_passing([72, 95, 88, 61, 79], 75)count_passing([50, 60, 70], 60)count_passing([10, 20], 90)count_passing([], 50)
Step 8 of 12Practice · What would you do?
What would you do?
What does this program print?
nums = [3, 8, 2, 5]
for n in nums:
total = 0
total += n
print(total)Step 9 of 12Learn
enumerate, zip and nested loops
A few tools make for loops even more useful.
enumerate() gives you a counter alongside each item, so you don't need a separate index variable:
for i, name in enumerate(["Ana", "Ben", "Cy"], start=1):
print(i, name) # 1 Ana / 2 Ben / 3 Cyzip() walks through two sequences side by side:
for item, price in zip(["tea", "cake"], [3.0, 4.5]):
print(f"{item}: {price:.2f}")Nested loops put one loop inside another. The inner loop runs completely for each pass of the outer loop, so the body runs (outer count) × (inner count) times. Printing a 3-by-4 grid takes 12 inner iterations.
for row in range(1, 4):
for col in range(1, 5):
print(row * col, end=" ")
print() # new line after each rowHere end=" " tells print to finish with a space instead of a new line.
One rule to protect yourself: don't add or remove items from a list while looping over it. The loop's position gets confused and items are skipped. Loop over a copy (for x in items[:]) or build a new list instead.
Step 10 of 12Compare
for or while?
| Aspect | for loop | while loop |
|---|---|---|
| Best when | You are going through a collection or know the number of repetitions | You repeat until a condition changes and do not know how many times |
| Typical examples | Every item in a list, every line in a file, 10 rounds of a game | Ask until input is valid, simulate until a target is reached, run until the user quits |
| Risk of running forever | Very low over a finite collection | Yes, if the condition never becomes false |
| Counter handling | Automatic (use range or enumerate) | Manual: initialize, test and update yourself |
Step 11 of 12Practice · Choose one
How many times does the body of for i in range(1, 10): run?
Step 12 of 12Practice · Work it out
What is the value of sum(range(1, 5))?
Lesson complete!