Loop patterns

Topic 4 of 4 in Loops6 min readBeginnerFree course

Overview

Most loops you’ll ever write follow one of a handful of patterns. Recognising them turns “how do I solve this?” into “which pattern is this?” — and once you know them, you’ll also see when a built-in function can do the job for you.

Four loop patterns you will use constantly. Accumulate: total = 0, then for p in prices: total += p. Count: count = 0, then for w in words: if len(w) > 5: count += 1. Find the best: best = scores[0], then for s in scores: if s > best: best = s. Build a new list: big = [], then for p in prices: if p > 10: big.append(p). Built-ins do the first three in one call — sum(prices), max(scores) — and comprehensions do the fourth.

1. Accumulate

Combine all items into one result. Start with the “empty” value for the operation, then update it for each item:

Python
total = 0
for price in prices:
    total += price

The same shape works for other operations — multiplication (start with 1), joining text (start with ""), or building a set.

Built-in: sum(prices).

2. Count

Count how many items meet a condition:

Python
long_words = 0
for word in words:
    if len(word) > 5:
        long_words += 1

Built-ins: len(items) counts everything; for a condition, sum(1 for w in words if len(w) > 5) (generator expressions are covered in Comprehensions), or items.count(value) for an exact value.

3. Find the best

Keep track of the best so far, and replace it whenever you find something better:

Python
best = scores[0]
for score in scores:
    if score > best:
        best = score

Start with the first item, not with 0 — if all scores were negative, 0 would wrongly win. To remember which item was best, track both:

Python
best_name, best_score = names[0], scores[0]
for name, score in zip(names, scores):
    if score > best_score:
        best_name, best_score = name, score

Built-ins: max(scores), min(scores), and max(students, key=…) to compare by a property (Functions as values).

4. Build a new list (filter and transform)

Create a new list from the items you want, possibly changed:

Python
expensive = []
for price in prices:
    if price > 10:
        expensive.append(price * 1.2)     # filter AND transform

Building a new list is much safer than removing items from the original while looping. Shortcut: a list comprehension, [p * 1.2 for p in prices if p > 10] (Comprehensions).

5. Check: any and all

Two more patterns answer yes/no questions about a collection:

Python
any_negative = False
for n in numbers:
    if n < 0:
        any_negative = True
        break

Built-ins: any(n < 0 for n in numbers) — is at least one true? — and all(n > 0 for n in numbers) — are they all true?

The built-in versions

Pattern Loop Built-in
total total += x sum(items)
count all count += 1 len(items)
largest / smallest best-so-far max(items), min(items)
sorted copy — sorted(items)
any / every flag + break any(...), all(...)
filtered/transformed list append in a loop list comprehension

Use the built-ins whenever they fit — they’re shorter, faster and harder to get wrong. But knowing the loop behind each one means you can handle the cases they don’t cover: “the best day and its name”, “the total of only shipped orders”, “the first three that match”.

Combining patterns

Real tasks combine several patterns in one loop:

Python
total = 0
count = 0
for order in orders:
    if order["status"] == "shipped":
        total += order["amount"]
        count += 1
average = total / count if count else 0

Note the guard against dividing by zero when nothing matched.

When you face a new problem, ask: am I combining everything, counting, looking for the best, checking, or building a new collection? Then write the matching pattern — or use the built-in.

Exercise

Analyse a week of steps

Given a week of daily step counts, write loops (no sum, max or min yet!) to compute: (1) the total steps; (2) how many days reached the 10,000 goal; (3) the best day’s count and which day it was; (4) a new list of the days (names) below 6,000 steps. Print each result. Then, below your loops, get results (1) and (3) again with built-in functions and check they match.

Python
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
steps = [8200, 11500, 5400, 10050, 3900, 14200, 9100]

# 1. Total (accumulate)

# 2. Days at or above 10,000 (count)

# 3. Best day (find the best)

# 4. Days below 6,000 (build a new list)

# 5. Check with built-ins

Summary

  • Accumulate: start with 0 (or an empty value) and add each item.
  • Count: start at 0 and add 1 when an item meets a condition.
  • Find the best: start with the first item and replace it whenever you find a better one.
  • Build a new list: start with [] and append the items you want — instead of changing the original.
  • Built-ins such as sum, max, min, len, any and all do common patterns in one call.