Nishaglobal Education logo

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.

Lesson 8 of 1430 minQuiz: 4 questions

🎯 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
  1. What you'll learn and why it matters
  2. Your first for loop
  3. Repeating a set number of times with range()
  4. Adding things up: the accumulator pattern
  5. Choosing items with if inside a loop
  6. Worked example: a class report
  7. Practice
  8. Common mistakes
  9. Recap
  10. Quiz
  11. Mark lesson complete

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

Python
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:

for fruit in fruits:"mango""banana""apple"1st2nd3rdone item each round, in orderRound 1: fruit = "mango"prints: I like mangoRound 2: fruit = "banana"prints: I like bananaRound 3: fruit = "apple"prints: I like appleNo items left → carry on: Done!
The loop takes the items one at a time, in order. Each time round, the variable fruit refers to the current item and the indented block runs. After the last item, the program carries on below the loop.
Time roundfruit isPrinted
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:

CodeNumbers 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)
Python
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.

Python
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:

Python
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

Python
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.

  1. Create total = 0 before the loop.
  2. Loop over range(len(prices)).
  3. Work out line = quantities[i] * prices[i], print it and add it to total.
  4. Print the total after the loop (not indented).
Show the solution
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
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 before stop.
  • Accumulator pattern: set a total before the loop, add to it inside, use it after.
  • Put an if inside 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. 1. How many times does `print` run? for n in range(3): print(n)

  2. 2. What does this print? total = 0 for x in [5, 10, 15]: total += x print(total)

  3. 3. A loop should add up prices but prints only the last price. What is the most likely cause?

  4. 4. Which numbers does `range(2, 8, 2)` produce?

Answer all 4 questions to check.

Mark this lesson complete

Finished this lesson?

When you have worked through the examples and exercises, mark it complete to save your progress.