Loop patterns
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.
1. Accumulate
Combine all items into one result. Start with the “empty” value for the operation, then update it for each item:
total = 0
for price in prices:
total += priceThe 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:
long_words = 0
for word in words:
if len(word) > 5:
long_words += 1Built-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:
best = scores[0]
for score in scores:
if score > best:
best = scoreStart with the first item, not with 0 — if all scores were negative, 0 would wrongly win. To remember which item was best, track both:
best_name, best_score = names[0], scores[0]
for name, score in zip(names, scores):
if score > best_score:
best_name, best_score = name, scoreBuilt-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:
expensive = []
for price in prices:
if price > 10:
expensive.append(price * 1.2) # filter AND transformBuilding 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:
any_negative = False
for n in numbers:
if n < 0:
any_negative = True
breakBuilt-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:
total = 0
count = 0
for order in orders:
if order["status"] == "shipped":
total += order["amount"]
count += 1
average = total / count if count else 0Note 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.
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.
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-insdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
steps = [8200, 11500, 5400, 10050, 3900, 14200, 9100]
# 1. Total (accumulate)
total = 0
for s in steps:
total += s
print("Total:", total) # 62350
# 2. Days at or above 10,000 (count)
goal_days = 0
for s in steps:
if s >= 10_000:
goal_days += 1
print("Goal reached on", goal_days, "days") # 3
# 3. Best day (find the best)
best = steps[0]
best_day = days[0]
for day, s in zip(days, steps):
if s > best:
best = s
best_day = day
print("Best:", best_day, best) # Sat 14200
# 4. Days below 6,000 (build a new list)
lazy_days = []
for day, s in zip(days, steps):
if s < 6000:
lazy_days.append(day)
print("Below 6,000:", lazy_days) # ['Wed', 'Fri']
# 5. Check with built-ins
print(sum(steps) == total, max(steps) == best) # True TrueSummary
- 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
[]andappendthe items you want — instead of changing the original. - Built-ins such as
sum,max,min,len,anyandalldo common patterns in one call.