Python - For Loops
Overview
Estimated time: 20–30 minutes
Use for loops with sequences, ranges, dictionaries, and custom iterables. Learn idiomatic patterns.
Learning Objectives
- Iterate over sequences, ranges, dicts, and files.
- Use enumerate,zip, and unpacking for clarity.
- Avoid index-based loops when iteration is clearer.
Prerequisites
Examples
for i in range(3):
    print(i)
names = ["Ada", "Grace", "Linus"]
for idx, name in enumerate(names, start=1):
    print(idx, name)
pairs = list(zip([1,2,3], ["a","b","c"]))
print(pairs)
Loop else clause
for x in [1,2,3]:
    if x == 4:
        print("found")
        break
else:
    print("not found")
Common Pitfalls
- Mutating a list while iterating over it; iterate over a copy or create a new list.
- Using range(len(seq))when direct iteration is clearer.
Checks for Understanding
- What does enumeratereturn?
- When does the elseblock on a loop run?
Show answers
- Pairs of (index, item).
- When the loop is not terminated by break.
Exercises
- Iterate over a dict and print keys and values.
- Use zipto merge two lists and print combined rows.