Loops & Iteration
Repeat work over entire datasets with for and while loops, enumerate and zip, list comprehensions, and the accumulator pattern.
Data science is repetition at scale: apply the same step to every row, every
file, every experiment. Copy-pasting a line five times doesn't scale to five
million — loops do. In this lesson you'll learn for and while, the
helpers range, enumerate, and zip, list comprehensions, and the
accumulator pattern that underlies nearly every summary statistic.
Why loops exist
Suppose you need to print a reminder five times. You could write five
print() calls... and then the requirement changes to fifty. A for loop
with range(n) runs its indented body n times:
Note that range(5) yields 0, 1, 2, 3, 4 — it starts at 0 and stops
before 5, exactly like list slicing. range(start, stop) and
range(start, stop, step) give you more control: range(2, 10, 2) is
2, 4, 6, 8.
Looping over collections
The real power move: for iterates directly over any collection — no index
bookkeeping needed. Lists yield items, strings yield characters, and
dictionaries yield keys:
Read for animal in animals aloud: "for each animal in animals". Choosing a
singular loop variable for a plural collection makes loops self-explanatory.
enumerate and zip
Two built-ins solve the most common loop chores. enumerate gives you the
index and the item — perfect for numbered output. zip walks two (or
more) lists in lockstep, pairing up corresponding items:
If you ever catch yourself writing for i in range(len(items)) just to do
items[i], reach for enumerate (need the index) or plain for item in items (don't) instead — same result, far more readable.
The accumulator pattern
Here is the single most important loop idiom in data work. To compute a total (or count, or running maximum), you: (1) create a variable before the loop, (2) update it on every iteration, (3) use it after the loop:
revenue += x is shorthand for revenue = revenue + x. Built-ins like
sum() are this exact pattern packaged up — but you'll constantly need
custom versions of it, like the conditional count above.
while: loop until a condition changes
A for loop runs once per item; a while loop keeps running as long as
its condition stays true. Use it when you don't know the number of
iterations in advance:
The body must move the condition toward False — here the balance grows
every pass. Forget that, and you get an infinite loop that never stops
(if it happens in a notebook, interrupt the kernel).
break and continue
Two keywords fine-tune any loop. break exits the loop immediately;
continue skips the rest of the current iteration and jumps to the next:
This is a very realistic pattern: skimming a data stream, skipping bad records, and bailing out on a fatal one.
Nested loops
A loop inside a loop: the inner loop runs completely for each pass of the outer one. That's how you cover every combination — every cell of a grid, every pair of items:
Nested loops multiply: 1000 × 1000 items means a million iterations. Fine for small data — but when things feel slow later in the course, a nested loop is often the culprit (and NumPy or pandas the cure).
List comprehensions
Python has a beloved shortcut for the "build a new list from an old one"
loop. A list comprehension packs create-loop-append into one readable
line, with an optional if to filter:
The template is [expression for item in collection if condition].
Comprehensions are everywhere in real Python code — use them for simple
transform/filter jobs, and fall back to a full loop when the logic needs
multiple statements.
Loops today, vectorization later
In the pandas and NumPy lessons ahead, many explicit loops disappear - df["price"] * 1.1 multiplies a million rows at once. But those tools are loops under the hood, and whenever logic gets too custom for them, you'll be back here. Master the patterns now.
Check your understanding
Q1.What numbers does range(5) produce?
Q2.You need both the position and the value of each list item. Which tool is most idiomatic?
Q3.Inside a loop over data records, what does continue do?
Q4.What's wrong with: total = 0 placed INSIDE the for loop body of an accumulator?
Q5.What does [s * 2 for s in [1, 2, 3] if s != 2] evaluate to?
Exercise: A weekly sales report
You have four weeks of sales, one list of sold items per week, in the dict
data shown in the hints/solution (weeks week1–week4 with items like
"pc", "laptop", "mouse"). Write (1) a function
total_sold(data, product) that loops over the dictionary and uses
.count() with an accumulator to return how many units of product were
sold across all weeks — verify "pc" → 9, "mouse" → 4, "keyboard" → 2.
Then (2) find which week sold the most items overall, and (3) build
the set of unique products ever sold.
That wraps up Python fundamentals — next module, you'll put these building blocks to work on real tabular data with NumPy and pandas.