HomeCourseModule 04 › for loops — doing something for every item

for loops — doing something for every item

Module 04 · Control Flow9 min readBeginner

What you'll learn

  • Write a for loop over a list and over a range
  • Use enumerate() to track position
  • Recognise when not to write a loop (vectorised operations)

The shape of a for loop

for name in ["Alice", "Bob", "Carol"]:
    print(f"Hello, {name}!")

Read it as: "for every name in this list, do the indented stuff." Three names → three greetings.

Looping a fixed number of times — range()

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

range(5) = 0, 1, 2, 3, 4. (Stops before 5 — Python's standard half-open style.)

range(1, 6)        # 1, 2, 3, 4, 5
range(0, 10, 2)    # 0, 2, 4, 6, 8

enumerate() — when you need the index

items = ["bread", "milk", "eggs"]
for i, item in enumerate(items, start=1):
    print(f"{i}. {item}")
# 1. bread
# 2. milk
# 3. eggs

Looping a dictionary

prices = {"bread": 3.50, "milk": 2.10, "eggs": 5.00}

for product, price in prices.items():
    print(f"{product}: ${price}")

break and continue

for n in range(20):
    if n % 2 != 0:   # odd
        continue
    if n > 12:
        break
    print(n)
# 0 2 4 6 8 10 12

Walkthrough: total a list of invoices

The data

invoices = [
    {"customer": "Acme",  "amount": 1200},
    {"customer": "Beta",  "amount":  800},
    {"customer": "Acme",  "amount":  300},
    {"customer": "Gamma", "amount": 1500},
]

Loop and accumulate

total = 0
for inv in invoices:
    total += inv["amount"]
print(total)   # 3800

total += inv["amount"] is shorthand for total = total + inv["amount"].

💡 The shortcut
For totals, Python gives you a built-in: sum(inv["amount"] for inv in invoices). We meet that pattern (a "generator expression") later.

When NOT to write a loop

If you're using pandas, you almost never need a manual loop. df["amount"].sum() beats writing out the loop in both speed and clarity. We'll see this everywhere from Module 9 onwards.

Key takeaways

  • for x in collection: — visit every item.
  • range(n) — loop n times.
  • enumerate() when you also need the index.
  • break stops the loop; continue skips to the next item.

FizzBuzz

For numbers 1 to 30: print "Fizz" if divisible by 3, "Buzz" if divisible by 5, "FizzBuzz" if both, otherwise the number. Classic interview question. You now know enough to write it.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.