DSM
50 XP
30 minsBeginner50 XP

For Loops

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

  • Write for loops over lists, strings, and range()
  • Build the three core accumulation patterns: sum, count, and find-extreme
  • Use enumerate() when you need the index alongside the value
  • Combine loops with conditionals to filter while iterating
  • Recognize when a loop should become a vectorized operation later

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

ShopifyNightly payout batches

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.

NASATelemetry frame processing

Ground software iterates over incoming telemetry frames, validating and decoding each one; malformed frames are counted and skipped inside the loop.

MailchimpCampaign sends

Sending a campaign is a loop over the subscriber list: personalize the template for each contact, send, and accumulate delivery stats.

Theory

The core ideas, in plain language.

The syntax mirrors English: `for item in collection:`. Python takes the first element, names it item, runs the indented block, then repeats with the next element until the collection is exhausted. You choose the variable name — pick one that describes a SINGLE element (price, row, name), not the plural.
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.

Analogy: The conveyor belt

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.

Key Concept
The accumulator pattern

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.4

total 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.

range() generates numbers to loop over: range(5) yields 0,1,2,3,4 (five numbers, starting at 0, stopping BEFORE 5 — same exclusive-stop rule as string slicing). range(1, 6) yields 1–5, and range(0, 20, 5) yields 0,5,10,15. Use range when you need to repeat something N times or generate index numbers.
Watch out
Don't modify a list while looping over it

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.

Visual Learning

See the concept, then explore it.

Anatomy of an accumulating loop

One pass of `for price in prices: total += price`. Click each stage to see the state change.

Worked Examples

Watch it built up, one line at a time.

Very EasyLoop over a list

Greet each member of a project team.

Step 1 of 2

A list of three names — the collection we'll iterate.

Code
01team = ['Amara', 'Jonas', 'Yuki']
Practice Coding

Your turn — write the code.

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().

Expected output
Reviews: 8
Average: 3.62
Positive: 5

Write your solution in the editor on the right, then hit Run.

Exercises

Prove it. Reach 80% to complete the lesson.

Mastery Gate0% / 80% required
Easy0/2 solved

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)

Medium0/3 solved

You need to print each item in a list alongside its 1-based position ('1. apples'). Which is the idiomatic tool?

ScenarioA teammate computes an average inside the loop: `for t in temps: avg = total / len(temps)` — updating avg on every single iteration. The result is correct but the reviewer asks for a change.

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).

1-based numbering:The first line must say Item 1, not Item 0
Currency formatting:Every price shows exactly 2 decimal places with a $ sign
Hard0/2 solved

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)'.

Tracks value and position:Both the max revenue and its day number must update together
Safe initialization:The champion starts as the first element, not 0
Complete 80% more exercises to unlock.
Interview Prep

How this shows up in real interviews.

Walk me through the accumulator pattern and name three aggregations built on it.

Show model answer

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?

Show model answer

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?

Show model answer

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.

scratchpad — preview this lesson's challenge anytime
reviews.pyPython
Ready
Output

Run your code to see the output here.