A dataset with a million rows doesn't care how clever your single if statement is — you need to visit every row. The for loop is how Python walks a collection, doing the same work to each item. Master it and you can process anything of any size with four lines of code.
What you'll learn
What
A for loop takes each item from a collection (a list, a string, a range of numbers) one at a time, assigns it to a variable, and runs a block of code for it. When the items run out, the loop ends.
Why
Almost everything in data work is a collection: rows, columns, files, API pages. Loops turn 'do this once' into 'do this for every record' — and the accumulation patterns you learn here (sum, count, find-max) are the mental model behind every aggregation you'll run in pandas and SQL.
Where it's used
Reading files line by line, cleaning each value in a column, computing totals and averages, batch API calls, and generating reports per customer.
Where this runs in production
A scheduled job loops over every merchant with a positive balance and creates one payout record each — a for loop with an if guard at its heart.
Ground software iterates over incoming telemetry frames, validating and decoding each one; malformed frames are counted and skipped inside the loop.
Sending a campaign is a loop over the subscriber list: personalize the template for each contact, send, and accumulate delivery stats.
daily_sales = [1250.0, 980.5, 1430.0]
for sale in daily_sales:
print(f'Sales: ${sale:.2f}')The loop body runs three times — once per element — with sale bound to 1250.0, then 980.5, then 1430.0. Singular name for the loop variable, plural for the collection: that one convention makes loops read like sentences.
A for loop is a conveyor belt through your workstation. Items arrive one at a time; you perform the same inspection on each; the belt stops when the last item has passed. You never grab two items at once, never skip ahead — and you don't control the belt, it feeds you.
Most useful loops build an answer as they go: initialize a variable BEFORE the loop (total = 0, count = 0, best = None), update it INSIDE the loop, use it AFTER. Sum, count, average, max, min — every aggregation in existence is this one pattern with a different update line.
temps = [21.5, 23.1, 19.8, 25.2]
total = 0.0
for t in temps:
total += t
average = total / len(temps)
print(round(average, 2)) # 22.4total starts at 0.0, grows by each temperature, and the average is computed after the loop finishes. The += operator (from the Operators lesson) is the workhorse of accumulation.
Removing items from a list you're currently iterating skips elements — the belt shifts under your feet. Build a NEW list of the items you want to keep instead (you'll meet the elegant one-line version in List Comprehensions). Also: loops in Python are the right tool for logic, but for pure math over large numeric arrays, remember Lists vs. NumPy Arrays — vectorized operations replace the loop entirely.
One pass of `for price in prices: total += price`. Click each stage to see the state change.
Greet each member of a project team.
A list of three names — the collection we'll iterate.
Your task
You have a list of product review scores (1–5 stars). Compute the number of reviews, the average score, and how many are 'positive' (4 stars or more). Use loops and the variables provided — no built-in sum().
Reviews: 8 Average: 3.62 Positive: 5
Write your solution in the editor on the right, then hit Run.
How many times does the body of `for i in range(4):` run?
What does this print? total = 0 for n in [2, 3, 4]: total += n print(total)
You need to print each item in a list alongside its 1-based position ('1. apples'). Which is the idiomatic tool?
What's the reviewer's point?
Given prices = [12.99, 4.50, 89.00, 23.75], print each price on its own line formatted as 'Item 1: $12.99' (1-based numbering, 2 decimal places).
To find the minimum of a list of temperatures that may all be negative, which initialization is correct?
A store logs daily revenue: revenues = [1200.0, 950.0, 1480.0, 1105.0, 890.0]. Using one loop, find the best day's revenue AND its 1-based day number, then print 'Best: $1480.00 (day 3)'.
Walk me through the accumulator pattern and name three aggregations built on it.
The accumulator pattern has three phases: initialize a result variable before the loop with a neutral value, update it inside the loop as each element passes, and read it after the loop ends. Sum initializes to 0 and adds each element; count initializes to 0 and adds 1 for matching elements; max/min initializes to the first element and replaces it whenever a better one appears. Average is sum divided by count after the loop. What makes the pattern important beyond loops is that it's the mental model for every aggregation you'll ever run — pandas' .sum(), SQL's COUNT(*), and Spark reducers are all industrial-strength accumulators.
Why is initializing max-finding with 0 a bug, and what's the correct approach?
Initializing the champion to 0 assumes at least one element exceeds 0. For data that can be entirely negative — temperatures, account balance changes, profit margins — no element beats 0, so the loop finishes with the answer 0, a value that isn't even in the data. The safe initialization is the first element of the collection (or None with an explicit `is None` check on the first iteration). The same reasoning applies to min-finding with any magic number. In an interview, spotting the sentinel-value bug and stating 'initialize from the data, not from an assumption' is exactly the defensive instinct being tested.
When would you replace a Python for loop with a vectorized NumPy/pandas operation, and when is the loop the right choice?
For elementwise math over large numeric collections — scaling a column, computing a derived field, filtering by a condition — vectorized operations are both faster (compiled C inner loop, no per-element interpreter overhead) and clearer (df['net'] = df['gross'] * 0.9 reads as intent). I reach for an explicit Python loop when the work per item is genuinely sequential or side-effectful: calling an API per record, writing files, complex branching logic that doesn't map to array operations, or when the collection is small enough that clarity beats microseconds. The honest rule: loops for orchestration and I/O, vectorization for math. Writing the loop first to understand the logic, then vectorizing it, is a normal and respectable workflow.
Common Mistakes to Avoid
1) Off-by-one with range(): range(5) is 0–4, and range(1, 5) is 1–4 — the stop is always excluded. 2) Initializing a max-accumulator to 0 when data can be negative. 3) Putting after-the-loop work (like computing an average) inside the loop body. 4) Modifying the list you're iterating — collect into a new list instead. 5) Shadowing the collection with the loop variable (for temps in temps:). 6) Using a loop for elementwise math on big arrays where NumPy vectorization is the tool.
Ask the AI Tutor
Try these prompts in the AI Tutor panel: • 'Give me five range() calls and quiz me on what they produce.' • 'Show me an accumulator bug where the initialization is wrong.' • 'When exactly should I use enumerate vs range(len(...))?' • 'Walk me through how this loop becomes a pandas one-liner.' • 'Interview mode: ask me to trace a loop's variables iteration by iteration.'
Glossary
Iteration — one pass through the loop body. Loop variable — the name bound to the current element (for PRICE in prices). Iterable — anything a for loop can walk: lists, strings, ranges, and more. range(start, stop, step) — generates a sequence of ints, stop excluded. Accumulator — a variable initialized before a loop and updated inside it to build a result. enumerate() — wraps an iterable to yield (index, item) pairs. .append() — list method that adds one element to the end. Tuple unpacking — assigning paired values to multiple names at once (for i, x in ...). argmax — the INDEX of the maximum element, not the maximum itself.
Recommended Resources
• Docs: 'for Statements' and 'The range() Function' in the official Python tutorial. • Read: 'Looping Techniques' in the same tutorial for enumerate, zip, and friends — a preview of tricks you'll keep using. • Practice: compute the total, count, average, max, AND min of one list in a single loop with five accumulators. • Next in DSM: for loops end when the collection does — While Loops run until a CONDITION says stop, the shape behind retries, polling, and convergence.
Recap
✓ for item in collection: visits every element once, in order. ✓ range(start, stop, step) generates number sequences; the stop is always excluded. ✓ The accumulator pattern (init before, update inside, use after) powers sum, count, average, and extremes. ✓ Initialize max/min hunts from the data (first element), never from 0. ✓ enumerate() delivers the index and the item together, with tuple unpacking. ✓ Filter inside a loop with if; collect survivors into a NEW list with .append(). Next up: While Loops. A for loop runs once per element — next you'll write loops that run until a condition changes, and learn to guarantee they actually stop.
Run your code to see the output here.