Another common pattern for working with lists is finding the largest or smallest value. We saw an example of code to do this earlier, but let’s break down the important parts of this recipe.
We need to have a “tracking variable” that will store the largest (or smallest value we have seen). The easiest way to initialize that variable is to use the first value from the list (index 0). When we are starting, the first value is the largest (or smallest) we have seen.
We then loop through the values and compare each to the highest value. If the current value is higher than the largest we have seen (or smaller than the lowest), we change our tracking variable to hold that new “best” value.
If we are not sure that the list has any items, we can’t start with the first item. In that case, we can start with some value that is so low (or high as appropriate) that we are confident the first item we do look at will be “better” and replace the starting one.
The program above could use 0 as the initial value for highest - the first value we see would be sure to be higher. But once we change the program to look for the lowest, we would have to change the starting value to 101 or something large to guarantee that any real values we looked at would be lower.
Sometimes the max or min pattern might need to be modified to work with values calculated from each item. Here is an example of adapting the basic recipe to find the longest name in a list of names: