Lists and Collections
A loop processes the collection one element at a time.
Four Questions for Every Collection
When a program processes a collection of values, four questions appear repeatedly: How many elements are there? What is their total? Which value is largest? Which value is smallest? Counting, summing, and finding extremes are common loop patterns for processing data. Each pattern keeps a variable whose state changes as the loop processes one element at a time.
The shared structure is initialize a variable before the loop, update it inside the loop using the current element, and use its final value after the loop completes.
Following Each Element
A loop processes the collection one element at a time. The current element changes on each iteration, while the counter and running total preserve information from earlier iterations. The counter records how many elements have been processed. The total records the sum of the values processed so far.
6
154Counters and Running Totals
Counting ignores the value of the current element. It starts a counter at 0 and increases that counter by 1 on every iteration. After the loop, the counter equals the number of elements processed. Summing uses a different update: it starts a total at 0 and adds the current element's value on every iteration.
| After processing | Current element | Counter | Running total |
|---|---|---|---|
| Before the loop | none | 0 | 0 |
| Element 1 | 3 | 1 | 3 |
| Element 2 | 41 | 2 | 44 |
| Element 3 | 12 | 3 | 56 |
| Element 4 | 74 | 4 | 130 |
| Element 5 | 5 | 5 | 135 |
| Element 6 | 19 | 6 | 154 |
A generated trace of count and total for six processed values.
Tracking Largest and Smallest
Extreme-finding patterns compare each current element with the best value found so far. For the maximum, update the stored value only when the current element is greater than it. For the minimum, update the stored value only when the current element is smaller than it.
74
3The initial value None means that no element has been stored yet. On the first iteration, the current element becomes the initial candidate for both extremes. Later elements are compared with that candidate. In the generated trace, 41 replaces 3 as the largest value, while 12 does not replace 3 as the smallest value. Eventually, 74 becomes the largest value, and 3 remains the smallest.
Tracing a Wrong Result
When a result is unexpected, trace the state instead of looking only at the final output. Record the accumulator or comparison variable before the loop and after every iteration. The first row where the trace differs from the expected behavior identifies where the logic went wrong.
total = 0
for current in values:
total = total + current
total = total + 1The extra update adds 1 during every iteration, so the error compounds as the loop continues.
total = 0
for current in values:
total = total + currentThe running total changes only by the current element's value.
| After processing | Expected total | Buggy total |
|---|---|---|
| Before the loop | 0 | 0 |
| 3 | 3 | 4 |
| 41 | 44 | 46 |
| 12 | 56 | 59 |
A partial trace shows the first incorrect state immediately after the first element.
Mistakes Beginners Make
Common mistake Starting the counter with a value other than 0
What it looks likecount = 1 before the loopWhy it failsThe counter already claims that an element has been processed before the loop begins.
Do this insteadInitialize the counter to 0, then increase it once per iteration.
Common mistake Adding the counter instead of the current element
What it looks liketotal = total + countWhy it failsA sum must accumulate each element's value, while the counter is used only to track how many elements have been processed.
Do this insteadUpdate the total with the current element.
Common mistake Updating the maximum or minimum without a comparison
What it looks likelargest = current on every iterationWhy it failsThe stored extreme would be replaced even when the current value is not more extreme.
Do this insteadFor the maximum, update only when the current element is greater. For the minimum, update only when it is smaller.
Common mistake Failing to handle the first comparison
What it looks likelargest = None followed only by current > largestWhy it failsNo element has been stored as the initial candidate yet.
Do this insteadAllow the first element to become the candidate when the stored value is None.
Common mistake Checking only the final result
Why it failsA final value does not show which iteration first produced an incorrect state.
Do this insteadTrace the variable before the loop and after every iteration.
Practice the Patterns
For a collection containing the values 8, 2, 11, and 5, write one loop that tracks the count, total, largest value, and smallest value. Before running it, predict the final state of all four variables. Then trace the state after each element.
Hints
- Initialize count and total to 0.
- Initialize largest and smallest to None.
- Increase count once per iteration and add the current element to total.
- Use a greater-than comparison for largest and a less-than comparison for smallest.
Tracing a Four-Element Collection
Determine the final count, total, largest value, and smallest value for 8, 2, 11, and 5.
- 1Initialize
Set count to 0, total to 0, largest to None, and smallest to None.
- 2Process 8
Count becomes 1 and total becomes 8. Because both extreme variables are None, largest and smallest become 8.
- 3Process 2
Count becomes 2 and total becomes 10. The maximum remains 8 because 2 is not greater than 8. The minimum becomes 2 because 2 is less than 8.
- 4Process 11
Count becomes 3 and total becomes 21. The maximum becomes 11. The minimum remains 2.
- 5Process 5
Count becomes 4 and total becomes 26. Neither extreme changes because 5 is between the stored minimum and maximum.
The final state is count 4, total 26, largest 11, and smallest 2.
Pattern Summary
- 1Counting starts a counter at 0 and increases it by 1 for every processed element.
- 2Summing starts a total at 0 and adds the current element's value on every iteration.
- 3Maximum tracking starts with None and replaces the stored value when the current element is greater.
- 4Minimum tracking starts with None and replaces the stored value when the current element is smaller.
- 5A manual trace of variable state after each iteration reveals where an unexpected result begins.
At a glance
- A collection-processing loop can count elements, accumulate a sum, or track extreme values.
- Each pattern initializes state before the loop and updates that state while processing the current element.
- Maximum and minimum patterns use comparisons against the best value seen so far.
- Tracing state after every iteration is a reliable way to locate logic errors.