Python Loop Patterns
What you will learn
- The counter, accumulator and running total patterns
- Tracking the biggest or smallest value and its position
- Searching with a flag and with
break - Building new lists by filtering and transforming
- Counting by category with a dictionary, unique items and grouping
- The built-in shortcuts for each pattern
Most loops you will ever write are one of a handful of patterns. Learn them as ready-made recipes. The examples use the same marks throughout (made-up numbers):
marks = [72, 85, 64, 91, 78, 55]
1. Counter: how many?
Start a count at 0, and add 1 for each item that fits:
passed = 0
for m in marks:
if m >= 70:
passed += 1
print("count >= 70:", passed)
count >= 70: 4
Quick check: what must the counter be before the loop starts?
0, set before the loop. Setting it inside the loop would reset it on every pass.
2. Accumulator: total, product and running total
An accumulator collects a result across the loop. Start from the neutral value: 0 for sums, 1 for products:
total = 0
for m in marks:
total += m
print(total, round(total / len(marks), 2))
prod = 1
for n in range(1, 6):
prod *= n
print(prod)
445 74.17
120
A running total keeps the total after every step, in a list:
running = []
t = 0
for m in marks:
t += m
running.append(t)
print(running)
[72, 157, 221, 312, 390, 445]
3. Biggest and smallest
Start with the first item, then compare each of the others:
best = marks[0]
worst = marks[0]
for m in marks[1:]:
if m > best:
best = m
if m < worst:
worst = m
print(best, worst)
91 55
If you also want where the biggest value is, remember its position:
best_i = 0
for i in range(1, len(marks)):
if marks[i] > marks[best_i]:
best_i = i
print(best_i, marks[best_i])
3 91
(Do not start with 0 as the "smallest so far": if every value is bigger than 0, you would never find the real minimum.)
4. Searching
To find an item, loop with break. A flag (or a position) records what you found:
target = 64
position = -1
for i, m in enumerate(marks):
if m == target:
position = i
break
print(position)
2
-1 means "not found", the same convention as the find method (lesson 4.4). A flag works for yes-or-no questions:
has_negative = False
for v in [3, 5, -2, 8]:
if v < 0:
has_negative = True
break
print(has_negative)
True
5. Building new lists
Start with an empty list and append to it. Two variations:
squares = []
for n in range(1, 6):
squares.append(n * n)
print(squares)
evens = []
for n in range(10):
if n % 2 == 0:
evens.append(n)
print(evens)
[1, 4, 9, 16, 25]
[0, 2, 4, 6, 8]
- Transform: append a changed value (
n * n). - Filter: append only when a condition holds (
n % 2 == 0).
Chapter 12 shows how list comprehensions do either in one line.
6. Counting by category
To count how often each value occurs, use a dictionary: the keys are the values and the numbers are the counts (dictionaries are chapter 9):
text = "mississippi"
freq = {}
for ch in text:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
print(freq)
{'m': 1, 'i': 4, 's': 4, 'p': 2}
The method get gives a default for a missing key, which shortens the loop:
freq = {}
for ch in text:
freq[ch] = freq.get(ch, 0) + 1
freq.get(ch, 0) is the current count, or 0 if the letter has not been seen yet.
7. Unique items and grouping
Unique items, keeping the order of first appearance:
seen = []
for v in [3, 1, 3, 2, 1]:
if v not in seen:
seen.append(v)
print(seen)
[3, 1, 2]
Grouping: collect items into lists by a key, here the first letter. setdefault creates the empty list the first time:
groups = {}
for w in ["apple", "avocado", "banana", "blueberry", "cherry"]:
groups.setdefault(w[0], []).append(w)
print(groups)
{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}
8. Skipping and stopping: sentinel values
Skip missing values with continue, and stop at a sentinel (an agreed "end" marker) with break:
data = [4, None, 8, None, 6]
s = 0
c = 0
for v in data:
if v is None:
continue
s += v
c += 1
print(s / c if c else 0)
total = 0
for text in ["5", "7", "done", "9"]:
if text == "done":
break
total += int(text)
print(total)
6.0
12
The average ignores the None values, and the if c else 0 avoids a division by zero (lesson 5.4). The second loop stops at "done", so the 9 is never added.
9. Built-in shortcuts
Python already has a tool for most patterns. Know both: the loop shows what happens, and the shortcut is shorter once you understand it:
| Pattern | Loop | Shortcut |
|---|---|---|
| total | total += m |
sum(marks) |
| biggest, smallest | compare and update | max(marks), min(marks) |
| any / all | flag and break |
any(...), all(...) (lesson 5.3) |
| running total | running.append(t) |
itertools.accumulate(marks) |
| counting values | dictionary and get |
collections.Counter(text) |
| first match | loop and break |
next(x for x in items if cond) |
| filter, transform | append in a loop |
list comprehension (chapter 12) |
import itertools
from collections import Counter
print(sum(marks), max(marks), min(marks))
print(list(itertools.accumulate(marks)))
print(Counter("mississippi").most_common(2))
print(next((w for w in ["a", "bb", "cccc"] if len(w) > 2), None))
445 91 55
[72, 157, 221, 312, 390, 445]
[('i', 4), ('s', 4)]
cccc
Use a loop when the task has extra steps or when you are still learning what is going on.
Worked example: a small class report
From the marks above, report the average, the best mark and who has it (by position), and how many students passed (50 or more) and how many scored 70 or more.
total = 0
best_i = 0
passed = 0
good = 0
for i, m in enumerate(marks):
total += m
if m > marks[best_i]:
best_i = i
if m >= 50:
passed += 1
if m >= 70:
good += 1
print(f"average {total / len(marks):.1f}")
print(f"best {marks[best_i]} (student {best_i + 1})")
print(f"passed {passed}, scored 70 or more {good}")
average 74.2
best 91 (student 4)
passed 6, scored 70 or more 4
| Pattern used | Variable |
|---|---|
| accumulator | total |
| position of the maximum | best_i |
| two counters | passed, good |
One loop updates all four. The student numbers and marks are made up.
Common mistakes
- Starting the counter or total inside the loop, so it resets every pass.
- Starting "smallest so far" at
0(or "biggest so far" at0when values may be negative). Start with the first item. - Dividing by
len(items)when the list may be empty. - Forgetting
breakin a search, so it keeps going and may overwrite the answer. - Creating a list inside the loop, so it is rebuilt empty on every pass.
Key takeaways
- Counter: start at
0, add1when the item fits. Accumulator: start at0(sum) or1(product). - Maximum or minimum: start from the first item, compare the rest; remember the position if you need it.
- Search: loop with
breakand a flag or position;-1means not found. - Build lists by appending transformed or filtered items; use a dictionary to count or group by a key.
- Python has shortcuts (
sum,max,any,Counter, comprehensions); learn the loop first, then the shortcut.
Practice
1. Write a loop that counts how many words in ["a", "bb", "ccc", "dd"] have length 2.
Show answer
count = 0
for w in ["a", "bb", "ccc", "dd"]:
if len(w) == 2:
count += 1
count is 2.
2. Use a loop to find the product of [2, 3, 4].
Show answer
prod = 1
for n in [2, 3, 4]:
prod *= n
prod is 24. Starting at 1, not 0, keeps the product from being zero.
3. Why is smallest = 0 a poor start for finding the smallest of [7, 3, 9]?
Show answer
No value is smaller than 0, so the loop would never update it and the answer would wrongly be 0. Start with the first item, smallest = nums[0].
4. Write a loop that builds the list of the lengths of the words in ["kiwi", "fig"].
Show answer
lengths = []
for w in ["kiwi", "fig"]:
lengths.append(len(w))
lengths is [4, 3].
5. Count how many times each word appears in ["a", "b", "a"] with a dictionary.
Show answer
counts = {}
for w in ["a", "b", "a"]:
counts[w] = counts.get(w, 0) + 1
counts is {'a': 2, 'b': 1}.
6. Which built-in gives the same result as an accumulator loop that adds all items?
Show answer
sum(items).