1.2.18 · D3Introduction to Programming (Python)

Worked examples — for loop — iterating over sequences

4,253 words19 min readBack to topic

Before anything, one word we will lean on constantly: a sequence is just an ordered line-up of things you can walk through left-to-right — like beads on a string. The for loop is the finger that touches each bead once, in order, and stops when there are no more beads.


The scenario matrix

Every for loop question is really one of these case classes. The last column tells you which worked example below covers that cell.

Case class What makes it tricky Example
Non-empty list the "happy path" Ex 1
Empty sequence (degenerate) body runs zero times Ex 2
Single-item sequence (limiting) body runs exactly once Ex 3
String → characters not a list, still a sequence Ex 4
range counting (start/stop/step) half-open, negative step Ex 5
Dict — keys vs values vs items three different loop targets Ex 6
Two sequences, unequal length zip stops at the shorter Ex 7
Index + value at once enumerate unpacking Ex 8
Nested loop (grid) inner runs fully per outer step Ex 9
Unordered iterable (set) / custom iterator order not guaranteed Ex 10
break / continue / for-else control flow early exit, skip, "ran to completion?" Ex 11
Real-world word problem translate words → loop Ex 12
Exam twist: mutate-while-looping cursor skips items Ex 13

Every numeric result below is machine-checked at the bottom of the page.


Worked examples


Recall Which construct for which case?

Empty sequence — body runs how many times? ::: Zero. for over [] is legal and does nothing. range(5, 0, -1) produces? ::: 5, 4, 3, 2, 1 — negative step counts down, stop (0) excluded. Iterating a dict directly gives? ::: The keys. Use .values() or .items() otherwise. zip over lengths 3 and 2 runs how many times? ::: 2 — it stops at the shorter sequence. Does looping a set guarantee order? ::: No — a set is unordered; only order-independent ops are safe. When does a for-else clause run? ::: Only when the loop finished without hitting a break. What does continue do? ::: Skips the rest of the current pass and jumps to the next item. Safe way to filter a list you're looping? ::: Build a new list (comprehension) or iterate a copy xs[:].


Connections

  • Parent: for loop (Hinglish) — the mechanism these cases exercise.
  • range function — Ex 5's half-open counting and negative steps.
  • Lists and indexing — Ex 1, 13: the sequence and the position cursor.
  • Strings as sequences — Ex 4: why looping a string yields characters.
  • Dictionaries — keys, values, items — Ex 6: three loop targets.
  • enumerate and zip — Ex 7, 8: pairing and counting cleanly.
  • List comprehensions — Ex 13's safe fix.
  • while loop — condition-based repetition — the desugared engine behind every case; break/continue work there too.
  • Iterators and generators — Ex 2, 10: StopIteration, sets, and custom iterators.

Concept Map

How to read this map: start at the top node "scenario matrix" — every branch below it is one case class from the table, in the same order you met the worked examples. Follow a branch down to see the one tricky idea that case teaches. The only branch that continues further is the mutate-while-looping case, whose arrow points to its fix (copy or comprehension) — a reminder that this is the one case where the naive approach is genuinely unsafe. Read it as a checklist: if you can name what each leaf means, you have covered every scenario on this page.

fix

scenario matrix

non-empty happy path

empty runs zero times

single runs once

string gives characters

range half-open and negative step

dict keys values items

zip stops at shorter

enumerate index and value

nested grid loop

set unordered and custom iterator

break continue and for-else

real world discount

mutate while looping skips

copy or comprehension