Finding Extremes: Maximum and Minimum Values in Loops
The central question is: what should the variable represent after each iteration? A counter represents how many items have been seen, a total represents the sum of the items seen, and an extreme variable represents the largest or smallest item seen so far.
Try it: Loop Tracer
How a Python for loop visits each item in turn, and how an accumulator variable (a total, a count, a best-so-far or a result list) changes on every iteration.
How it works
- Initialise the accumulator before the loop.
- Each iteration, the loop variable takes the next value from the list.
- An if inside the loop decides whether to update the accumulator.
- After the last item the loop ends and the accumulator holds the answer.
Default run (13 steps): values = [4, 9, 2, 7, 5]. Run the loop one statement at a time. … The loop has used every value. print(total) shows 27.
Simplified: A model of five fixed loop programs (sum, count, maximum, minimum, filter) run on your list — it steps the program exactly as Python would, but it does not run Python.
Loading the simulation…
Why Running Results Matter
A loop examines one item at a time, but many tasks require information from all the items examined so far. You might count the items, add their values, or keep the largest or smallest value encountered. An accumulator is the variable that makes this possible: it starts before the loop, changes during each iteration, and holds the final result when the loop ends.
Finding an extreme value appears in many data tasks. A weather application may find the highest temperature recorded during a week, a sales system may identify the lowest-priced item, and a fitness tracker may find a maximum heart rate during a workout.
The central question is: what should the variable represent after each iteration? A counter represents how many items have been seen, a total represents the sum of the items seen, and an extreme variable represents the largest or smallest item seen so far.
The Accumulator Pattern
Every accumulator loop has three parts. First, initialize the accumulator before the loop. Second, update it inside the loop on every iteration. Third, use its value after the loop finishes. The update must match the question being answered. Counting adds 1 for every item, while summing adds the current item's actual value.
values = [4, 9, 2]
count = 0
total = 0
for value in values:
count += 1
total += value
print(count)
print(total)- 1count starts at 0 and increases by 1 for each item.
- 2total starts at 0 and increases by the current value.
- 3After the loop, count is 3 and total is 15.
3
15| Task | Initial value | Update inside the loop | Meaning after each iteration |
|---|---|---|---|
| Counting | 0 | count += 1 | Number of items seen so far |
| Summing | 0 | total += value | Sum of values seen so far |
The update determines what the accumulator represents.
Tracing Each Iteration
Tracing a Running Total
Find the count and total for the values 4, 9, and 2.
- 1Before the loop
count is 0 and total is 0. No items have been processed.
- 2After 4
count becomes 1. total becomes 0 + 4, which is 4.
- 3After 9
count becomes 2. total becomes 4 + 9, which is 13.
- 4After 2
count becomes 3. total becomes 13 + 2, which is 15.
The final count is 3 and the final total is 15.
A useful trace records the accumulator after each item. If a total suddenly returns to zero, or if a counter changes by more than 1, the trace exposes the problem. The accumulator should not be reset inside the loop; it should carry its previous value into the next iteration.
Common mistake Initializing the accumulator inside the loop
What it looks likefor value in values: total = 0 total += valueWhy it failsThe previous total is discarded on every iteration, so the variable does not accumulate all the values.
Do this insteadSet total = 0 before the loop, then update total inside the loop.
Common mistake Adding 1 when the task is summing
What it looks likefor value in values: total += 1Why it failsThis counts iterations instead of adding the current item's value.
Do this insteadUse total += value for a numeric total.
Common mistake Using the item value when the task is counting
What it looks likefor value in values: count += valueWhy it failsThe result depends on the values rather than on how many items were processed.
Do this insteadUse count += 1 for counting.
The Largest-So-Far Pattern
To find a maximum, maintain a variable that represents the largest value seen so far. For each new item, update that variable only when the new item is strictly larger. The condition has two parts: largest is None handles the first item, and value > largest handles later comparisons.
12In the example, the first item becomes the initial largest value because largest is None. The next item, 3, does not replace 7. The value 12 does replace it because 12 is larger. The final value, 5, leaves the result unchanged. The variable always describes the largest value encountered up to that point.
The Smallest-So-Far Pattern
The minimum pattern has the same structure as the maximum pattern. Initialize smallest to None, then replace it when the current item is strictly smaller. The only comparison change is from the greater-than operator to the less-than operator: if smallest is None or value < smallest.
3Tracing the Minimum
Find the smallest value in the sequence 8, 2, 6, and 1.
- 1Before the loop
smallest is None, so no value has been selected yet.
- 2After 8
Because smallest is None, 8 becomes the current smallest value.
- 3After 2
2 is smaller than 8, so smallest becomes 2.
- 4After 6
6 is not smaller than 2, so smallest remains 2.
- 5After 1
1 is smaller than 2, so smallest becomes 1.
The final smallest value is 1.
Why None Starts the Search
None marks the extreme variable as empty before any item has been examined. On the first iteration, the None part of the condition is true, so the first item becomes the initial largest or smallest value. Later iterations can use ordinary numeric comparisons.
Built-In Functions in Practice
| Manual pattern | Built-in function | Use in practical code |
|---|---|---|
| Counting loop | len(values) | Prefer len() for the number of items. |
| Summing loop | sum(values) | Prefer sum() for the total of numeric items. |
| Maximum loop | max(values) | Prefer max() for the largest value. |
| Minimum loop | min(values) | Prefer min() for the smallest value. |
Manual loops reveal the underlying patterns; built-ins are the practical choice for these basic tasks.
4
27
12
3The built-in functions produce the same kinds of results as the manual patterns while being shorter and clearer for these specific tasks. The manual loops are still worth learning because they expose the algorithm, support tracing and debugging, and transfer to situations where a ready-made function does not provide the exact operation you need.
Practice the Patterns
Write a loop that examines values = [11, 4, 18, 6]. Keep track of the largest value and the smallest value. Before running the code, write down the value of each variable after every iteration.
Hints
- Initialize largest and smallest to None before the loop.
- Use value > largest for the maximum comparison.
- Use value < smallest for the minimum comparison.
For the same list, decide which version is clearer in practical Python code: a manual counting loop or len(values), a manual summing loop or sum(values), and a manual extreme-finding loop or max(values) and min(values). Explain why the manual versions are still useful to understand.
Hints
- Use the built-in functions for these basic operations in real code.
- Use manual loops to study the accumulator and comparison patterns.
- Check that your trace never resets the accumulator inside the loop.
Common mistake Using the wrong comparison operator
What it looks likeUsing value < largest when searching for a maximum
Why it failsThe loop may keep smaller values instead of larger ones.
Do this insteadUse > for largest and < for smallest.
Common mistake Updating the extreme on every iteration
What it looks likelargest = value without a comparisonWhy it failsThe variable becomes the most recently examined item, not the largest item seen so far.
Do this insteadUpdate only when the new value is strictly more extreme.
Common mistake Forgetting the None initialization case
What it looks likeif value > largest when largest is None
Why it failsThe first item needs a way to become the initial extreme before an ordinary comparison can be made.
Do this insteadUse largest is None or value > largest, and use the analogous condition for smallest.
Pattern Summary
- 1Initialize an accumulator before the loop and update it inside the loop without resetting it.
- 2Counting adds 1 for every item, while summing adds the current item's value.
- 3For a maximum, keep the largest value seen so far and update with a strictly larger item.
- 4For a minimum, keep the smallest value seen so far and update with a strictly smaller item.
- 5Use None to let the first item establish the initial extreme, and prefer
len(),sum(),max(), andmin()for these basic operations in practical Python code.
At a glance
- An accumulator persists across iterations and holds a result when the loop ends.
- Counting and summing use different updates: increment by 1 for counting and add the item for summing.
- Maximum and minimum loops compare each new item with the current extreme.
- None allows the first item to become the initial maximum or minimum.
- Use Python's built-in functions for straightforward counting, summing, and extreme-finding tasks.