Python Loop Patterns
Loop patterns are reusable loop shapes for common jobs.
Accumulator: build a total
Total starts at zero. Each price is added to it.
prices = [10, 20, 15]
total = 0
for price in prices:
total += price
print(total)Counter: count the matches
Passes starts at zero. It grows only when a score passes.
scores = [70, 45, 90, 50]
passes = 0
for score in scores:
if score >= 50:
passes += 1
print(passes)Collector: gather the chosen items
Evens starts as an empty list. Each even number joins it with +.
numbers = [1, 2, 3, 4]
evens = []
for number in numbers:
if number % 2 == 0:
evens = evens + [number]
print(evens)Best-so-far: keep the winner
Hottest starts with the first value. A warmer value takes its place.
temperatures = [18, 24, 21, 27]
hottest = temperatures[0]
for temperature in temperatures:
if temperature > hottest:
hottest = temperature
print(hottest)Example
prices = [24, 9, 42, 15, 31]
total = 0
for price in prices:
total += price
print("Total:", total)
count = 0
for price in prices:
count += 1
print("Count:", count)
largest = prices[0]
for price in prices:
if price > largest:
largest = price
print("Most expensive:", largest)Key points
- Pattern: a loop shape you can reuse for many jobs
- Accumulator: a value that grows step by step, such as a total
- Counter: a value that counts how many items match
- Collector: a value that gathers chosen items into one result
- Best-so-far: a value that keeps the best item seen so far
In this example, prices holds five prices. The first loop adds each price into total. It prints a total of 121. The second loop counts one for each price. It prints a count of 5. The third loop starts largest with the first price, 24. A price takes its place only when it is bigger. The largest price found is 42, so that prints last.
Note
For best-so-far, start with the first item, not zero.
Zero would wrongly win if every value were negative.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
You need the highest score in a list. Which pattern fits best?