University of Free Knowledge
QA 76.73 · fol. 8

Once for Each Item

A for loop binds a variable to each item a sequence like range() hands it, running the body exactly once per item. · 12 min

A while loop repeats until a condition fails. Very often, though, you already know exactly what you want to repeat over: every number from 1 to 10, every name in a list, every character in a word. For that, Python offers the for loop. It takes a sequence of items and runs its body once for each item, binding a loop variable to the current item on each pass. When the sequence runs out, the loop ends — no counter to update by hand, no condition to get wrong. The most common sequence to loop over is one you generate on the spot with range().

Guess before you learn

Read before you run it: for i in range(3): print(i) What does this print, top to bottom?

THE DEPTH DIAL — the same idea, younger or deeper
9–12

9–12

range has a three-argument form, range(start, stop, step): it begins at start, adds step each time, and stops before reaching stop. The interval is half-open — start included, stop excluded — so the count of values is stop - start when the step is 1.

Prefer a for loop over a while loop whenever the number of passes is known ahead of time: the loop variable and the update are handled for you, which removes the two most common while-loop mistakes — forgetting the update and misplacing the boundary. You can also loop directly over a list or a string, item by item.

range()

A generator of a sequence of whole numbers. range(n) counts from 0 up to but not including n, giving n values in all.

CALLVALUES IT PRODUCESHOW MANYrange(3)0, 1, 23range(1, 5)1, 2, 3, 44range(0, 10, 2)0, 2, 4, 6, 85range(5, 0, -1)5, 4, 3, 2, 15
PLATE I range() reference — it always starts at the first value and stops before the last.
Retrieval Gate — answer before you continue 0 / 4

1.What does range(4) produce?

2.How many times does the body run? for i in range(6): print(i)

3.What is the last value i takes in for i in range(2, 6):?

4.In one sentence, say what range(n) produces and how many values it gives.

Counting from 0 feels off by one at first, but it has a clean payoff: range(n) gives exactly n values, and range(len(items)) gives exactly one index for each item. Inside the body, you usually use the loop variable — to print it, add it to a running total, or reach an item by its position. Watching that variable take each value in turn is how you trace a for loop.

Ink That Thinks — guess first; the answer draws itself.
This loop keeps a running total: total = 0 for i in range(1, 5): total = total + i Before reading on, place a point for the value of total after each pass — pencil your guesses first, then check the shape.

01234502.557.510pass numbervalue of total
Tap to place each point.
PLATE II A running total over range(1, 5) — guess in graphite, truth in ink.

Trace this for loop, one pass at a time — the steps fade as you master them

1
Before the loop, total = 0. First pass: range(1, 4) hands i its first value. What is i on this pass?
i = 1
2
Run the body: total = total + i = 0 + 1. What is total now?
total = 1
3
Second pass: i becomes 2. Run the body: total = total + i = 1 + 2. What is total now?
total = 3
4
Third pass: i becomes 3, and total = 3 + 3. Then range(1, 4) is exhausted, so the loop ends. What is the final total?
total = 6
Why is this true?

Why does range(1, 5) stop at 4 instead of reaching 5?

Because range uses a half-open interval: the start value is included but the stop value is excluded. range(1, 5) therefore hands out 1, 2, 3, 4 and stops before 5. This is deliberate — it makes range(0, n) give exactly n values and range(len(x)) give exactly one index per item.

PASSITOTAL BEFORETOTAL AFTER110122133336
PLATE III Tracing a for loop: one row per item, the loop variable stepping through range(1, 4).
Retrieval Gate — answer before you continue 0 / 4

1.Trace this loop. What is total at the end? total = 0 for i in range(1, 6): total = total + i

2.How many times does for i in range(2, 7): run its body?

3.When is a for loop the better choice over a while loop?

4.Without looking back: what does a for loop do each pass, and what does range(n) produce?

You now have both kinds of repetition: the while loop that runs on a condition, and the for loop that runs once per item. Between them they cover nearly every repeating task you will meet. What remains is precision — reading a loop so carefully that you can name its every value and catch the boundary slips before they cost you. That is the whole of the next folio.

Note

Off-by-one on range still biting? The Atelier of Mind drills the count of range(a, b) until b - a is second nature.

Practice — new ink and old, interleaved

1.Review from folio 6: how many branches of an if / elif / else chain run each time it is reached?

2.score = 72. if score >= 90: g='A' / elif score >= 70: g='B' / elif score >= 50: g='C' / else: g='F'. What is g?

3.Which grouping does Python use for not True and False?

4.What does this loop print, in order? for k in range(3, 0, -1): print(k)

5.How many times does the body run? i = 0 while i < 5: i = i + 1

6.Review from folio 2: after x = 6 then x = x + x, what is the value of x?

7.Say in your own words how a for loop knows when to stop.

8.Trace: what is total after this loop? total = 0 for i in range(4): total = total + 2

9.Review from folio 7: does this loop stop, and if so, what is the final n? n = 1 while n < 8: n = n + 3

The Call Slip — search everything Ctrl·K / ⌘K