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

  1. What does enumerate return?
  2. When does the else block on a loop run?
Show answers
  1. Pairs of (index, item).
  2. When the loop is not terminated by break.

Exercises

  1. Iterate over a dict and print keys and values.
  2. Use zip to merge two lists and print combined rows.