“Do this to every element” is half of all programs ever written. Traversal is the loop that visits an entire list, one element at a time — and paired with the accumulator, it’s where lists finally pay off.
This is today’s lesson exactly — the for-each traversal. Enrolled in our Runestone course? Open it from there so your progress counts.
Still in Programs. You have loops (Week 1) and lists (3.6–3.7). Traversal is where they combine: a loop that walks a list end to end. Drop an accumulator inside and you can sum, count, or search a whole collection.
Python’s for item in list hands you
each element directly — no index needed. It reads almost like English, and it’s the
cleanest way to touch every value in a collection.
Traversal means visiting every element of a list in order. The clean way is the for-each loop, which gives you the value each pass — no index arithmetic:
scores = [85, 90, 78] total = 0 for s in scores: total = total + s print(total) # 253
scores ← [85, 90, 78] total ← 0 FOR EACH s IN scores { total ← total + s } DISPLAY(total) /* 253 */
Hover or tap a line to light its twin. This is traversal + accumulator: the loop supplies each score, the accumulator adds it. Trace it — total goes 0 → 85 → 175 → 253.
for s in scores) hands you the
value — best when you just need each value. Index-based
(for i in range(len(scores)), then use scores[i]) hands you the position
— needed when you must know where you are, or change the list as you go.
Step through a traversal and watch the loop hand over each element while the accumulator updates. Switch the job to see the same traversal sum or count.
for s in scores /
FOR EACH s IN scores) — no index needed.Five questions. Trace the traversal element by element, updating the accumulator as you go, then pick your answer.
Total a store’s daily sales, average a million survey answers, scan every transaction for fraud, apply a filter to every pixel — all traversal. The phrase “for each” is doing the heavy lifting behind analytics, recommendations, and search. One clean loop, applied to a collection of any size.
It’s also where scale becomes visible. The same for-each that sums three scores in an instant takes real time over three billion — which is why Unit 4 asks how long algorithms take, and Unit 5 asks how we handle data too big to look at all at once.