Programming fundamentals · Beginner · 15 min
Loop over lists, ranges and dictionaries with for
By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim
You will use Python's for loop with range, enumerate, zip and dictionary items, fix an off-by-one error, skip and stop with continue and break, and finish with a script that prints a multiplication table and a class attendance report.
On this page
A loop repeats lines of code. Python has two kinds. A while loop repeats as long as a condition stays true, which suits "keep going until something happens". A for loop goes through a collection one item at a time: every number in a range, every name in a list, every entry in a dictionary. Most loops you write will be for loops, because most of the time you already have the things you want to go through.
In this tutorial you write one short script per idea and run each one, so you see exactly what the loop does. You print a times table, number a list of names, pair two lists, walk a dictionary, skip and stop items, and make one deliberate mistake that every programmer makes at least once. You finish with a script that prints a multiplication table and an attendance report for a small class.
Every command uses python3. If your command is python3.15 or py, type that instead. If you are learning on an Android phone, the Termux app runs Python and every script here; the scripts are a few hundred bytes each and need no downloads after Python is installed.
Step 1 · Print a times table with range
Make a folder to work in and write your first for loop:
mkdir -p ~/for-loops-demo
cd ~/for-loops-demo
cat > times.py <<'PY'
number = 7
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
print("done")
PY
python3 times.pyLine by line:
number = 7is the table you want.for i in range(1, 11):is the loop.range(1, 11)produces the whole numbers from 1 up to, but not including, 11. On each pass, Python puts the next number into the variableiand runs the indented block. The nameiis your choice;iis a common habit for a counter.- The colon at the end of the
forline and the four-space indent on the next line are required. The indented lines are the loop body: they run once per number. print(f"...")uses an f-string, so the values ofnumber,iandnumber * iare placed inside the text.print("done")is not indented, so it runs once, after the loop has finished.
Check it worked
You see ten lines, from 7 x 1 = 7 to 7 x 10 = 70, then done on its own line. Change number to 12 and run it again: the table changes, the loop does not.
Step 2 · Make an off-by-one error and fix it
range stops before its end value. That rule is consistent, but it catches everyone at first. Write a version where the end looks right but is not:
cd ~/for-loops-demo
cat > off_by_one.py <<'PY'
for i in range(1, 10):
print(f"9 x {i} = {9 * i}")
PY
python3 off_by_one.py
python3 off_by_one.py | wc -lYou meant "1 to 10", wrote 10 as the end, and got one line too few. This is an off-by-one error: the loop ran once more or once less than intended. The last line is 9 x 9 = 81, and wc -l counts 9 lines.
Fix it by making the end one more than the last number you want:
cat > off_by_one.py <<'PY'
for i in range(1, 11):
print(f"9 x {i} = {9 * i}")
PY
python3 off_by_one.py | tail -n 1
python3 off_by_one.py | wc -lA useful way to read range(start, stop): it gives you stop - start numbers. range(1, 11) gives 10. With one argument, range(5) starts at 0 and gives 0, 1, 2, 3 and 4, which is five numbers. With a third argument, range(0, 50, 10) counts in steps of 10: 0, 10, 20, 30, 40.
Check it worked
After the fix, the last line is 9 x 10 = 90 and the count is 10. If you still see 9 x 9 = 81, check that you saved the file with 11, not 10.
Step 3 · Walk a list of names with enumerate
A for loop can go straight through a list. You do not need a counter to read the items:
cd ~/for-loops-demo
cat > names.py <<'PY'
students = ["Amara", "Kwame", "Zainab", "Thandiwe", "Chidi"]
for name in students:
print("Hello,", name)
print()
for position, name in enumerate(students, start=1):
print(f"{position}. {name}")
PY
python3 names.pyThe first loop puts each string from students into name, in order, and greets it. The list is not changed.
The second loop adds numbers. enumerate(students, start=1) hands the loop a pair on every pass: a count and the item. for position, name in ... unpacks that pair into two variables. Without start=1 the count begins at 0, which is how Python numbers list positions, but people reading a register expect 1. The empty print() writes a blank line between the two outputs.
You may see older code that writes for i in range(len(students)): and then students[i]. It works, but enumerate says the same thing more clearly and cannot point past the end of the list.
Check it worked
The output is five Hello, lines, a blank line, and then a numbered list from 1. Amara to 5. Chidi.
Step 4 · Pair two lists with zip
Data often comes as two lists that line up: names in one, scores in the other. zip walks both at once:
cd ~/for-loops-demo
cat > pairs.py <<'PY'
students = ["Amara", "Kwame", "Zainab", "Thandiwe", "Chidi"]
days_present = [20, 17, 19, 12, 20]
for name, days in zip(students, days_present):
print(f"{name:<10} {days:>2} days")
short_list = [20, 17]
print(len(list(zip(students, short_list))), "pairs from a short list")
try:
for name, days in zip(students, short_list, strict=True):
pass
except ValueError as err:
print("strict zip:", err)
PY
python3 pairs.pyzip(students, days_present) gives ("Amara", 20) first, then ("Kwame", 17), and so on, and the loop unpacks each pair into name and days. In the f-string, :<10 pads the name to 10 characters, left-aligned, and :>2 right-aligns the number in 2 characters, so the columns line up.
The second half shows the trap. When the lists have different lengths, zip stops quietly at the shorter one: five names and two numbers give two pairs and no warning. Passing strict=True makes Python raise a ValueError instead, which is what you want when the lists must match. pass is a statement that does nothing; the loop body is empty because only the error matters here.
Check it worked
You see five aligned lines such as Amara 20 days, then 2 pairs from a short list, then a line starting strict zip: followed by Python's message that one argument is shorter than the other.
Step 5 · Loop over a dictionary with items
A dictionary stores values under keys, such as each student's days present under their name. Looping over a dictionary directly gives you the keys. Use .items() to get each key with its value:
cd ~/for-loops-demo
cat > register.py <<'PY'
register = {"Amara": 20, "Kwame": 17, "Zainab": 19, "Thandiwe": 12, "Chidi": 20}
for name in register:
print(name)
print()
total = 0
for name, days in register.items():
total = total + days
print(f"{name}: {days}")
print("Average days present:", total / len(register))
PY
python3 register.pyThe first loop prints only the names. The second unpacks each (key, value) pair from register.items() into name and days, adds the days to a running total and prints the pair. After the loop, total / len(register) divides by the number of entries. Python dictionaries keep the order you inserted the keys in, so the output follows the order written in the code.
Names from any language work as keys. "Ngozi", "Thandiwe" and "Tomé" are all ordinary strings in Python 3, which stores text as Unicode.
Check it worked
You see the five names, a blank line, five name: days lines and Average days present: 17.6.
Step 6 · Skip with continue and stop with break
Two keywords change the flow inside a loop. continue skips the rest of the body and moves to the next item. break leaves the loop entirely:
cd ~/for-loops-demo
cat > flow.py <<'PY'
register = {"Amara": 20, "Kwame": 17, "Zainab": None, "Thandiwe": 12, "Chidi": 20}
for name, days in register.items():
if days is None:
print(f"{name}: no record, skipped")
continue
print(f"{name}: {days}")
print()
for name, days in register.items():
if days is not None and days < 15:
print(f"First student below 15 days: {name}")
break
else:
print("Everyone has at least 15 days")
PY
python3 flow.pyNone is Python's value for "nothing here", used for a student with no record. In the first loop, continue jumps straight to the next student, so the print below it does not run for Zainab.
The second loop searches. As soon as it finds a student under 15 days, it prints the name and break ends the loop, so Chidi is never checked. The else attached to the for (lined up with for, not with if) runs only when the loop ends without a break, which makes it a tidy way to say "not found". Change Thandiwe's 12 to 16 and run it again to see the else line.
Check it worked
The first block prints Zainab: no record, skipped and no Zainab: None line. The second block prints First student below 15 days: Thandiwe.
Step 7 · See when while is still the right choice
for needs something to go through. When you do not know in advance how many passes you need, and the loop should stop when a condition changes, while fits better. Compare the two:
cd ~/for-loops-demo
cat > which_loop.py <<'PY'
weekly_savings = [1500, 2000, 1200, 1800]
total = 0
for amount in weekly_savings:
total = total + amount
print("Saved over four weeks:", total)
target = 10000
saved = 0
weeks = 0
while saved < target:
saved = saved + 1500
weeks = weeks + 1
print(f"Saving 1500 a week reaches {target} after {weeks} weeks")
PY
python3 which_loop.pyThe first question has a fixed set of items, the four weekly amounts, so for goes through them and stops by itself. The second asks "how many weeks until I reach the target?". The number of passes is the answer, not something you know at the start, so while repeats until saved < target is no longer true.
A quick rule: if you can name the collection, use for. If you can only name the stopping condition, such as reaching a total or the user typing done, use while. The tutorial on keeping a loop going with while goes further with that second kind.
Check it worked
The output is Saved over four weeks: 6500 and Saving 1500 a week reaches 10000 after 7 weeks. Six weeks gives 9000, which is still short, so the loop runs a seventh time.
Step 8 · Build the table and attendance report script
Put the pieces together in one script. It prints a multiplication table for any number you pass on the command line, then an attendance report that numbers the class, flags anyone below 80 per cent, skips missing records and lists who had full attendance:
cd ~/for-loops-demo
cat > report.py <<'PY'
import sys
number = int(sys.argv[1]) if len(sys.argv) > 1 else 7
print(f"Times table for {number}")
for i in range(1, 11):
print(f"{number:>3} x {i:>2} = {number * i:>4}")
school_days = 20
students = ["Amara", "Kwame", "Zainab", "Thandiwe", "Chidi"]
days_present = [20, 17, None, 12, 20]
register = {}
for name, days in zip(students, days_present, strict=True):
register[name] = days
print()
print(f"Attendance over {school_days} days")
below = 0
for position, (name, days) in enumerate(register.items(), start=1):
if days is None:
print(f"{position}. {name:<10} no record")
continue
percent = days / school_days * 100
flag = " <- below 80%" if percent < 80 else ""
if flag:
below = below + 1
print(f"{position}. {name:<10} {days:>2}/{school_days} {percent:5.1f}%{flag}")
full = []
for name, days in register.items():
if days == school_days:
full.append(name)
print()
print("Below 80%:", below)
print("Full attendance:", ", ".join(full))
PY
python3 report.py 6What is new here, and where each idea came from:
sys.argvis the list of words on the command line.sys.argv[1]is the first word after the script name,6in this run, andint()turns it into a number. With no argument the table defaults to 7.- The times table is the
range(1, 11)loop from the first step, with widths such as:>3so the columns line up. zip(..., strict=True)builds theregisterdictionary from the two lists and refuses to run if they ever get out of step.enumerate(register.items(), start=1)combines two earlier steps. Each pass gives a number and a(name, days)pair, so the loop variables are writtenposition, (name, days)with brackets around the pair.continueskips the percentage for a student with no record, so the code never dividesNone.:5.1fshows the percentage with one decimal place in a five-character column.- The last loop collects names into a new list with
append, and", ".join(full)turns that list into one line of text.
Check it worked
The output starts with Times table for 6 and ten lines ending in 6 x 10 = 60. The report then shows:
Attendance over 20 days
1. Amara 20/20 100.0%
2. Kwame 17/20 85.0%
3. Zainab no record
4. Thandiwe 12/20 60.0% <- below 80%
5. Chidi 20/20 100.0%
Below 80%: 1
Full attendance: Amara, ChidiRun python3 report.py with no number to get the 7 times table.
Common beginner mistakes
- Forgetting the colon or the indent.
for i in range(3)without:is aSyntaxError. A body that is not indented givesIndentationError: expected an indented block. - Indenting a line that should run once. A
printof the total inside the loop prints a running total on every pass. Move it back to theforcolumn to print it once at the end. - Off by one with range. The end value is never included. Ask "how many numbers do I want?" and check that
stop - startmatches. - Changing a list while looping over it. Removing items from the same list you are looping over skips some of them. Loop over the original and build a new list, as the full-attendance loop does.
- Expecting zip to complain. Without
strict=True, lists of different lengths are cut to the shortest without warning.
When you are finished, delete the demo folder:
cd ~
rm -rf ~/for-loops-demoNext steps
- Practise
whileloops with a program that keeps asking for input until you typedone: keep asking for expenses with a while loop. - Use a
forloop over a list of dictionaries to summarise real spending: store expenses in a list and show a summary. - Pick out parts of a list instead of looping over all of it: index, slice, sort and search lists in Python.
- Combine a loop and a dictionary to count things: count words in a text with a dictionary.
Part of these paths
Related tutorials
- Keep asking for expenses until the user is doneYou will turn the budget tracker into a program that asks for expense after expense with a while loop, stops when you type done, and prints the total, how many expenses you entered and what is left.
- Index, slice, sort and search lists in PythonYou will use a list of market prices to practise indexing, slicing, adding and removing items, searching, sorting and a first list comprehension, and end with a script that answers five questions about the prices.
- Count words in a text with a dictionaryYou will count how often each word appears in a text, first with a plain Python dictionary, then with .get() and collections.Counter, and finish with a script that prints the most common words in any text file.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials