Python tutorials · Part 5 of 8

The Python for loop, and how range() works

A for loop repeats a block of code once for every item in a sequence. With range() it becomes a counted loop. Here's how both work, with examples you can run.

A for loop in Python takes a collection of values and runs the same block of code once for each value, in order. You don't manage a counter or check a condition yourself: Python hands you the next item every time round, and stops when there are none left.

That one idea covers most of the repetition you'll ever write. Print every line of a file, add up a list of prices, try ten different settings for a model: all of them are for loops.

The basic for loop

Here is a list of daily step counts, and a loop that prints each one:

week = [8200, 10450, 6300, 12000]

for steps in week:
    print(steps)
8200
10450
6300
12000

Read the first line as plain English: for each value in week, call it steps, and run the indented block. Three parts make up every for loop:

  • for starts the loop.
  • steps is the loop variable. Python binds it to the first item, runs the block, then rebinds it to the next item, and so on. You choose the name; pick one that says what each item is.
  • in week names the iterable: the thing Python takes items from.

The colon and the indentation matter. Everything indented under the for line is the body of the loop and runs once per item. The first line that isn't indented runs once, after the loop has finished.

week = [8200, 10450, 6300, 12000]
total = 0

for steps in week:
    total = total + steps

print("Total:", total)
Total: 36950

This is the accumulator pattern: start a variable at zero (or an empty list) before the loop, update it inside the loop, use it after. You'll write it constantly.

Looping over strings and other iterables

A for loop works on anything iterable, not just lists. A string gives you one character at a time:

for letter in "data":
    print(letter.upper())
D
A
T
A

Tuples, sets, dictionaries, files and range() are all iterable too. Looping over a dictionary gives you its keys; use .items() to get keys and values together:

prices = {"apple": 0.5, "bread": 1.2}

for item, price in prices.items():
    print(item, price)
apple 0.5
bread 1.2

How range() works

When you need to repeat something a fixed number of times, or need the numbers themselves, use range(). It produces a sequence of whole numbers without building a list in memory.

for i in range(5):
    print(i)
0
1
2
3
4

Two things surprise beginners: range(5) starts at 0, and it stops before 5. You get five numbers, 0 to 4. The stop value is never included.

range() takes up to three arguments: range(start, stop, step).

print(list(range(2, 6)))        # start at 2, stop before 6
print(list(range(0, 10, 3)))    # every third number
print(list(range(10, 0, -2)))   # counting down
[2, 3, 4, 5]
[0, 3, 6, 9]
[10, 8, 6, 4, 2]

With a negative step, range() counts down, and it still stops before the stop value. To count down from 5 to 1, write range(5, 0, -1).

range(len(...)): when you need the position

Sometimes you want each item and its position. Beginners often write this:

names = ["Asha", "Ben", "Chen"]

for i in range(len(names)):
    print(i, names[i])
0 Asha
1 Ben
2 Chen

It works, but Python has a cleaner tool for it.

enumerate() and zip()

enumerate() gives you the position and the item together:

names = ["Asha", "Ben", "Chen"]

for position, name in enumerate(names, start=1):
    print(position, name)
1 Asha
2 Ben
3 Chen

zip() walks through two (or more) sequences side by side, pairing their items:

names = ["Asha", "Ben", "Chen"]
scores = [82, 74, 91]

for name, score in zip(names, scores):
    print(f"{name}: {score}")
Asha: 82
Ben: 74
Chen: 91

zip() stops at the end of the shortest sequence, so mismatched lengths won't raise an error. They'll quietly drop the extra items, which is worth knowing when you debug.

Nested loops

A loop inside a loop runs the inner loop completely for every pass of the outer one:

for row in range(1, 4):
    line = ""
    for col in range(1, 4):
        line += str(row * col) + " "
    print(line)
1 2 3 
2 4 6 
3 6 9 

The inner body runs 3 × 3 = 9 times. Nested loops multiply quickly: two loops over 10,000 items each is 100 million passes. When a nested loop feels slow, there's usually a better data structure (a set or dictionary) or a vectorised NumPy operation that avoids it.

Common mistakes

Expecting range() to include the stop value. range(1, 10) gives 1 to 9. If you want 1 to 10, write range(1, 11).

Changing a list while looping over it. Removing items from the list you're looping over makes Python skip elements, because the positions shift under the loop. Build a new list instead:

nums = [1, 2, 2, 3]
kept = [n for n in nums if n != 2]
print(kept)
[1, 3]

Forgetting the colon or the indentation. Python needs the : at the end of the for line and a consistent indent for the body. A missing indent raises an IndentationError.

Reusing the loop variable after the loop and expecting it to be reset. After the loop ends, the loop variable still holds the last item. That's occasionally useful and often a source of bugs.

Using range(len(x)) everywhere. If you only need the items, loop over them directly. If you need positions too, use enumerate().

Practice

  1. Print the even numbers from 2 to 20 using range() with a step.
  2. Given words = ["model", "data", "loss"], print each word with its length.
  3. Count how many vowels are in the string "machine learning".

Answers

for n in range(2, 21, 2):
    print(n, end=" ")
print()

for word in ["model", "data", "loss"]:
    print(word, len(word))

count = 0
for ch in "machine learning":
    if ch in "aeiou":
        count += 1
print(count)
2 4 6 8 10 12 14 16 18 20 
model 5
data 4
loss 4
6

Where this shows up in machine learning

Training a model is a loop: for each epoch, for each batch of data, compute predictions, measure the error and adjust the weights. Hyperparameter searches are loops over candidate settings, and cross-validation is a loop over folds. Libraries like NumPy and pandas hide many loops inside fast vectorised operations, but you'll still write for loops around them, and reading library code is far easier once loops feel natural.

First Principles, the SchoolWhool newsletter

One machine learning idea, explained properly, every week.

The intuition, the common mistake, and a five-minute way to try it yourself. Written by Gaurav.