for loops: repeating work for every item
Repeat code for every item in a Python list with a for loop, count with range(), add up totals with an accumulator, and filter items with if inside a loop.
🎯 By the end of this lesson you will be able to:
- Write a for loop that processes every item in a list
- Use range() to repeat something a set number of times
- Build totals and new lists inside a loop
Outline
What you'll learn and why it matters
Computers are brilliant at doing the same job many times without getting bored or making mistakes. A loop repeats a block of code. The for loop repeats it once for every item in a list. Whether you have 3 items or 3 million, the code is the same length.
Your first for loop
fruits = ["mango", "banana", "apple"]
for fruit in fruits:
print(f"I like {fruit}")
print("Done!")Output
I like mango I like banana I like apple Done!
Read the loop as plain English: for each fruit in the list fruits, print a sentence. Here is exactly what Python does:
| Time round | fruit is | Printed |
|---|---|---|
| 1 | "mango" | I like mango |
| 2 | "banana" | I like banana |
| 3 | "apple" | I like apple |
| (no items left) | - | Done! (after the loop) |
The name after for (here fruit) is a normal variable that you choose. Name it as the singular of the list's name: for fruit in fruits, for price in prices. That makes loops read like sentences.
Repeating a set number of times with range()
Sometimes you do not have a list; you just want to repeat something 5 times, or count from 1 to 10. range() produces a sequence of numbers for a loop:
| Code | Numbers produced |
|---|---|
range(5) | 0, 1, 2, 3, 4 (five numbers, starting at 0) |
range(1, 6) | 1, 2, 3, 4, 5 (stops before 6) |
range(0, 20, 5) | 0, 5, 10, 15 (steps of 5) |
for number in range(1, 6):
print(f"7 x {number} = {7 * number}")Output
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35
Adding things up: the accumulator pattern
One of the most useful loop patterns: start a variable at zero before the loop, then add to it inside the loop. The variable is called an accumulator.
prices = [120, 90, 450, 299]
total = 0
for price in prices:
total = total + price
print(f"Added {price}, running total {total}")
print(f"Grand total: {total}")Output
Added 120, running total 120 Added 90, running total 210 Added 450, running total 660 Added 299, running total 959 Grand total: 959
total += price is a shorter way to write total = total + price. You will see += a lot in real code.
Choosing items with if inside a loop
Put an if inside a loop to act only on some items. Here we build a new list of the expensive items, using append from the last lesson:
prices = [120, 90, 450, 299, 1200]
expensive = []
for price in prices:
if price > 250:
expensive.append(price)
print(expensive)
print(f"{len(expensive)} items cost more than 250")Output
[450, 299, 1200] 3 items cost more than 250
Notice the two levels of indentation: the if belongs to the loop, and expensive.append(price) belongs to the if.
Worked example: a class report
names = ["Asha", "Ravi", "Meera", "John"]
marks = [78, 91, 38, 84]
passed = 0
for i in range(len(names)):
if marks[i] >= 40:
result = "pass"
passed += 1
else:
result = "needs support"
print(f"{names[i]}: {marks[i]} ({result})")
print(f"{passed} of {len(names)} passed")Output
Asha: 78 (pass) Ravi: 91 (pass) Meera: 38 (needs support) John: 84 (pass) 3 of 4 passed
range(len(names)) gives the indexes 0, 1, 2, 3, so names[i] and marks[i] are the matching name and mark. (In lesson 11 you will meet dictionaries, a neater way to keep names and marks together.)
Practice
Guided exercise
Shopping bill
You have quantities = [2, 1, 3] and prices = [45, 120, 30] for three items. Print the cost of each line and the total bill.
- Create
total = 0before the loop. - Loop over
range(len(prices)). - Work out
line = quantities[i] * prices[i], print it and add it tototal. - Print the total after the loop (not indented).
Show the solution
quantities = [2, 1, 3]
prices = [45, 120, 30]
total = 0
for i in range(len(prices)):
line = quantities[i] * prices[i]
print(f"Item {i + 1}: {line}")
total += line
print(f"Total: {total}")Output
Item 1: 90 Item 2: 120 Item 3: 90 Total: 300
How to get there: Each time round, i is the index of one item. We add 1 when printing because people count items from 1, not 0. The total is printed once, after the loop has finished.
Your turn
Count the long words
Given words = ["cat", "elephant", "sun", "giraffe", "python"], print each word that has more than 4 letters, then print how many there were.
Show the solution
words = ["cat", "elephant", "sun", "giraffe", "python"]
count = 0
for word in words:
if len(word) > 4:
print(word)
count += 1
print(f"{count} long words")Output
elephant giraffe python 3 long words
How to get there: This combines a loop, an if and a counter that starts at 0 before the loop.
Common mistakes
Setting the total to 0 inside the loop
You see: The total only shows the last item
Fix: Move total = 0 above the for line.
Indenting the final print by mistake
You see: The total is printed after every item instead of once
Fix: Lines that should run once after the loop go back to the left margin.
Forgetting the colon after the for line
You see: SyntaxError: expected ':'
Fix: Every for line ends with :.
Expecting range(5) to include 5
You see: The loop stops at 4
Fix: range stops before the end number. Use range(1, 6) for 1 to 5.
Changing a list while looping over it
You see: Items are skipped in surprising ways
Fix: Build a new list instead, as in the filtering example.
Recap
for item in my_list:runs the indented block once for each item, in order.range(start, stop)produces numbers for counting loops; it stops beforestop.- Accumulator pattern: set a total before the loop, add to it inside, use it after.
- Put an
ifinside a loop to act only on the items you want.
Key terms
- Loop
- Code that repeats a block several times.
- Iteration
- One time round a loop.
- Accumulator
- A variable that builds up a result, such as a total, across a loop.
Check your understanding
Answer all 4 questions, then check your answers to see an explanation for each one.
1. How many times does `print` run? for n in range(3): print(n)
2. What does this print? total = 0 for x in [5, 10, 15]: total += x print(total)
3. A loop should add up prices but prints only the last price. What is the most likely cause?
4. Which numbers does `range(2, 8, 2)` produce?
Mark this lesson complete
Finished this lesson?
When you have worked through the examples and exercises, mark it complete to save your progress.