Concepts / Finding Extremes: Maximum and Minimum Values in Loops

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.

  • Programming
Interactive lab

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

  1. Initialise the accumulator before the loop.
  2. Each iteration, the loop variable takes the next value from the list.
  3. An if inside the loop decides whether to update the accumulator.
  4. 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.

Educational simulation

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.

In the real world

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.

Key point

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.

Code walkthrough
values = [4, 9, 2]

count = 0
total = 0

for value in values:
    count += 1
    total += value

print(count)
print(total)
  1. 1
    count starts at 0 and increases by 1 for each item.
  2. 2
    total starts at 0 and increases by the current value.
  3. 3
    After the loop, count is 3 and total is 15.
Output
3
15
count = 0before loopcount = 3after 3 itemstotal = 0before looptotal = 15after 4 + 9 + 2incrementadd values
What does each accumulator hold before the loop and after every item has been processed?
TaskInitial valueUpdate inside the loopMeaning after each iteration
Counting0count += 1Number of items seen so far
Summing0total += valueSum of values seen so far

The update determines what the accumulator represents.

Tracing Each Iteration

Worked example

Tracing a Running Total

Find the count and total for the values 4, 9, and 2.

  1. 1
    Before the loop

    count is 0 and total is 0. No items have been processed.

  2. 2
    After 4

    count becomes 1. total becomes 0 + 4, which is 4.

  3. 3
    After 9

    count becomes 2. total becomes 4 + 9, which is 13.

  4. 4
    After 2

    count becomes 3. total becomes 13 + 2, which is 15.

Result

The final count is 3 and the final total is 15.

Key point

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 like
    for value in values:
        total = 0
        total += value
    Why it fails

    The previous total is discarded on every iteration, so the variable does not accumulate all the values.

    Do this instead

    Set total = 0 before the loop, then update total inside the loop.

  • Common mistake

    Adding 1 when the task is summing

    What it looks like
    for value in values:
        total += 1
    Why it fails

    This counts iterations instead of adding the current item's value.

    Do this instead

    Use total += value for a numeric total.

  • Common mistake

    Using the item value when the task is counting

    What it looks like
    for value in values:
        count += value
    Why it fails

    The result depends on the values rather than on how many items were processed.

    Do this instead

    Use 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.

python
Output (expected)
12
Nonelargest7largest = 73largest = 712largest = 125largest = 12first item3 is not larger12 is larger5 is not larger
How does the current maximum change as each item is examined, and when does it stay the same?

In 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.

python
Output (expected)
3
Worked example

Tracing the Minimum

Find the smallest value in the sequence 8, 2, 6, and 1.

  1. 1
    Before the loop

    smallest is None, so no value has been selected yet.

  2. 2
    After 8

    Because smallest is None, 8 becomes the current smallest value.

  3. 3
    After 2

    2 is smaller than 8, so smallest becomes 2.

  4. 4
    After 6

    6 is not smaller than 2, so smallest remains 2.

  5. 5
    After 1

    1 is smaller than 2, so smallest becomes 1.

Result

The final smallest value is 1.

Why None Starts the Search

Definition

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.

Noneno item seen8first item2later item2smallest so farfirst item selectedcompare next item2 is smaller
Why does the first item become the initial maximum or minimum when the variable starts as None?

Built-In Functions in Practice

Manual patternBuilt-in functionUse in practical code
Counting looplen(values)Prefer len() for the number of items.
Summing loopsum(values)Prefer sum() for the total of numeric items.
Maximum loopmax(values)Prefer max() for the largest value.
Minimum loopmin(values)Prefer min() for the smallest value.

Manual loops reveal the underlying patterns; built-ins are the practical choice for these basic tasks.

python
Output (expected)
4
27
12
3

The 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

MEDIUM

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.
EASY

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 like

    Using value < largest when searching for a maximum

    Why it fails

    The loop may keep smaller values instead of larger ones.

    Do this instead

    Use > for largest and < for smallest.

  • Common mistake

    Updating the extreme on every iteration

    What it looks like
    largest = value without a comparison
    Why it fails

    The variable becomes the most recently examined item, not the largest item seen so far.

    Do this instead

    Update only when the new value is strictly more extreme.

  • Common mistake

    Forgetting the None initialization case

    What it looks like

    if value > largest when largest is None

    Why it fails

    The first item needs a way to become the initial extreme before an ordinary comparison can be made.

    Do this instead

    Use largest is None or value > largest, and use the analogous condition for smallest.

Pattern Summary

  1. 1
    Initialize an accumulator before the loop and update it inside the loop without resetting it.
  2. 2
    Counting adds 1 for every item, while summing adds the current item's value.
  3. 3
    For a maximum, keep the largest value seen so far and update with a strictly larger item.
  4. 4
    For a minimum, keep the smallest value seen so far and update with a strictly smaller item.
  5. 5
    Use None to let the first item establish the initial extreme, and prefer len(), sum(), max(), and min() 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.

Related concepts

More concepts starting with F