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?
It prints 0, 1, 2. range(3) produces three numbers, and it starts at 0, so it hands out 0, 1, 2 and stops before 3. If you expected 1, 2, 3 — or 0 through 3 — keep that mark: range starting at 0 and stopping one early is the detail this folio pins down.
9–12
3–5
A for loop goes through a sequence one item at a time. for name in names: runs the body once for each name, and each time, name holds the next item in turn.
To loop a fixed number of times, use range(). range(4) produces the numbers 0, 1, 2, 3 — four numbers, counting from 0. So for i in range(4): runs its body four times, with i equal to 0, then 1, then 2, then 3.
6–8
A for loop has the shape for VARIABLE in SEQUENCE: followed by an indented body. Each pass, the loop variable is bound to the next item of the sequence, and the body runs once. There is no manual counter and no condition — the loop ends automatically when the sequence is exhausted.
range(n) yields the whole numbers from 0 up to but not including n: that is n values, 0, 1, ..., n-1. range(a, b) starts at a and stops before b. Because it stops one short of the end value, range(1, 5) gives 1, 2, 3, 4 — not 5.
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.
K–2
For each thing in a group, do one thing. For each friend at the table, hand out one plate. Five friends, five plates — one turn each, then you are done.
A for loop is the same idea. It walks through a group one item at a time and runs your steps once for each item. When the group is finished, the loop is finished.
Undergrad
A for loop iterates over any iterable: a range, a list, a string, a file. Each pass rebinds the loop variable to the next element and runs the body; when the source signals it is exhausted, the loop terminates. Counting is just the special case of iterating over a range.
range is not a list — it is a lazy sequence that computes each value on demand, so range(10**9) costs almost nothing until you actually iterate. A for loop is equivalent to a while loop over an explicit index, but it moves the index management into the language, where it cannot be got wrong.
Postgrad
The for loop is defined by the iterator protocol: for x in s obtains an iterator from s via iter, repeatedly calls next for each element, and terminates when next raises StopIteration. The loop is thus structural traversal of a possibly lazy stream, not arithmetic on an index.
This is why termination is guaranteed for any finite iterable without a separate variant argument: the loop stops exactly when the source is exhausted. range is an arithmetic-sequence object supporting this protocol in constant space, and looping over it is the idiomatic, off-by-one-resistant replacement for the manual counter loop.
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.
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.
Trace this for loop, one pass at a time — the steps fade as you master them
total = 0. First pass: range(1, 4) hands i its first value. What is i on this pass?i = 1
total = total + i = 0 + 1. What is total now?total = 1
i becomes 2. Run the body: total = total + i = 1 + 2. What is total now?total = 3
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.
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.
A for loop stops when the sequence it is walking through runs out of items; it runs the body once for each item and no more.
How close were you? Grade yourself honestly — it sets your review date.
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