Skip to content
Kuza Ndoto Academy

For Loops

Beginner → IntermediateChapter 3 · Page 16 of 564 min readUpdated 15 Nov 2026

A for loop repeats a block of code once for every item in a sequence, such as each letter of a word, each number in a range or each name in a list. It is the loop you'll use most often in Python.

Looping through a list

A list is an ordered collection of values written inside square brackets, separated by commas. (Lists get their own page in the next chapter: Lists.) A for loop visits each item in turn:

subjects = ["Maths", "English", "Biology"]

for subject in subjects:
    print("Revise", subject)

print("Revision plan done")
Revise Maths Revise English Revise Biology Revision plan done

On each pass (called an iteration), the loop variable subject takes the next value from the list, and the indented block runs once. When the items run out, the loop ends. You choose the loop variable's name; pick one that describes a single item.

for subject in subjects: subjects "Maths" "English" "Biology" Pass 1 subject = "Maths" Pass 2 subject = "English" Pass 3 subject = "Biology" Revise Maths Revise English Revise Biology
Figure 1. One pass per item, in order. On each pass the loop variable takes the next item and the body prints one line; after the third item the loop ends.

Looping a set number of times with range()

range() produces a sequence of whole numbers. It has three forms:

  • range(stop): from 0 up to, but not including, stop.
  • range(start, stop): from start up to, but not including, stop.
  • range(start, stop, step): counting in steps of step, which can be negative.
for i in range(3):
    print("Attempt", i + 1)
Attempt 1 Attempt 2 Attempt 3

To see all the numbers a range produces at once, convert it to a list:

print(list(range(5)))
print(list(range(1, 6)))
print(list(range(2020, 2031, 5)))
print(list(range(10, 0, -2)))
[0, 1, 2, 3, 4] [1, 2, 3, 4, 5] [2020, 2025, 2030] [10, 8, 6, 4, 2]
Common mistake

Expecting range() to include the stop value. range(1, 5) gives 1, 2, 3 and 4, but not 5. To count from 1 to 10, write range(1, 11).

Looping through a string

A string is a sequence of characters, so a for loop can visit each one. This program counts the vowels in a word:

word = "Mombasa"
vowels = 0

for letter in word:
    if letter.lower() in "aeiou":
        vowels += 1

print(word, "has", vowels, "vowels")
Mombasa has 3 vowels

Accumulating results

A very common pattern is to set up a variable before the loop and update it on every iteration. This is called an accumulator.

expenses = [350, 1200, 80, 2500]   # in KES
total = 0

for amount in expenses:
    total += amount

print(f"Total spent: KES {total}")

total_1_to_100 = 0
for n in range(1, 101):
    total_1_to_100 += n
print(total_1_to_100)
Total spent: KES 4130 5050

The same pattern finds the largest value: keep track of the best so far and replace it when you see something bigger.

scores = [72, 85, 64, 90, 58]
highest = scores[0]          # start with the first score

for score in scores:
    if score > highest:
        highest = score

print("Highest score:", highest)
Highest score: 90

(Python's built-in sum() and max() do these two jobs for you, but writing the loop yourself teaches the pattern behind them.)

Getting the position with enumerate()

enumerate() gives you each item together with its position. Use start=1 to count from 1 instead of 0.

tasks = ["Wake up", "Gym", "Study"]

for number, task in enumerate(tasks, start=1):
    print(number, task)
1 Wake up 2 Gym 3 Study

Looping over two lists together with zip()

zip() pairs up items from two (or more) sequences, so you can loop over them side by side.

names = ["Amina", "Brian", "Chebet"]
scores = [78, 64, 91]

for name, score in zip(names, scores):
    print(f"{name}: {score}")
Amina: 78 Brian: 64 Chebet: 91

If the sequences have different lengths, zip() stops at the end of the shortest one.

Note

After a for loop finishes, the loop variable keeps the last value it was given. After the subjects loop above, subject still holds "Biology". Avoid relying on this; it makes code harder to follow.

Common mistake

Adding or removing items from a list while looping over that same list. The loop can skip items or behave unexpectedly. Loop over a copy instead, or build a new list, as shown on the Comprehensions page.

Key points

  • for item in sequence: runs the block once per item in a list, string or range.
  • range(start, stop, step) produces numbers up to, but not including, stop.
  • Accumulator variables collect totals, counts and maximums across a loop.
  • enumerate() adds positions; zip() walks several sequences together.
  • Use break and continue for finer control of a loop (that's the next page).
Up next · Control FlowBreak, Continue & PassTake control of how loops run.
→

Tip: use the ← and → keys to move between pages.