Home / Learn / Code for makers

Python for loops: range, enumerate, zip, break and else

Python for loops: enumerate numbering a list of parts, and zip pairing resistor values with tolerances, with the printed output
Beginner

A for loop repeats a block of code once for each item in something: a list, a string, a range of numbers or the keys of a dictionary. These are the patterns you'll use every day. Every example was run on Python 3.13 and the output is copied from the run.

Counting with range()

for i in range(5):
    print(i, end=" ")
print()
for i in range(2, 11, 2):
    print(i, end=" ")
print()
for i in range(10, 0, -3):
    print(i, end=" ")
print()
print(list(range(0)))
0 1 2 3 4
2 4 6 8 10
10 7 4 1
[]

range(stop) counts from 0 up to, but not including, stop. range(start, stop, step) lets you choose where to start and how big each step is, including negative steps to count down. end=" " makes print put a space after each number instead of starting a new line.

Loop over the items themselves

parts = ["resistor", "LED", "capacitor"]
for part in parts:
    print(part)
resistor
LED
capacitor

If you find yourself writing for i in range(len(parts)): and then parts[i], loop over the list directly instead. It's shorter and harder to get wrong.

Need the position too? Use enumerate()

for number, part in enumerate(parts, start=1):
    print(f"{number}. {part}")
1. resistor
2. LED
3. capacitor

Two lists side by side: zip()

values = [220, 330, 1000]
tolerances = [5, 1, 1]
for r, tol in zip(values, tolerances):
    print(f"{r} Ω ±{tol}%")
220 Ω ±5%
330 Ω ±1%
1000 Ω ±1%

zip stops at the end of the shorter list.

Stop early with break, and the loop else

readings = [3.29, 3.31, 0.02, 3.30]
for i, v in enumerate(readings):
    if v < 1.0:
        print(f"Reading {i} is low: {v} V")
        break
else:
    print("All readings OK")
Reading 2 is low: 0.02 V

break leaves the loop immediately. The else block belongs to the for, not the if: it runs only if the loop finished without hitting break. It's handy for "search, and say if nothing was found".

Skip an item with continue

for v in readings:
    if v < 1.0:
        continue
    print(v, end=" ")
print()
3.29 3.31 3.3 

Notice 3.30 prints as 3.3: Python doesn't keep trailing zeros. Use an f-string like f"{v:.2f}" when you want a fixed number of decimal places.

Dictionaries

pins = {"LED": 25, "buzzer": 16}
for name, pin in pins.items():
    print(name, pin)
LED 25
buzzer 16

More on dictionaries in Python lists and dictionaries.

Build a list in one line: comprehensions

squares = [n * n for n in range(1, 6)]
print(squares)
high = [v for v in readings if v > 3.3]
print(high)
[1, 4, 9, 16, 25]
[3.31]

A while loop, for comparison

count = 0
while count < 3:
    print("count is", count)
    count += 1
count is 0
count is 1
count is 2

Use for when you're going through a collection or a known number of steps, and while when you keep going until something changes, like waiting for a button. Forgetting count += 1 gives a loop that never ends; press Ctrl+C to stop it.

The classic bug: removing items while looping

items = [2, 4, 6, 7]
for x in items:
    if x % 2 == 0:
        items.remove(x)
print(items)
[4, 7]

The aim was to remove every even number, but 4 survived. Removing an item shifts the rest left, so the loop skips the one after it. Build a new list instead:

items = [2, 4, 6, 7]
items = [x for x in items if x % 2 != 0]
print(items)
[7]

Sources

The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.