Accumulating a Maximum ValueΒΆ

Now let’s take a detour for a moment, and see how we can use the accumulator pattern to compute the maximum value in a list. Then you’ll have an exercise to find the key in a dictionary that has the largest associated value.

To accumulate the maximum value in a list, you can have your accumulator variable keep track of the max-so-far. Initialize it to the first item in the list. Then iterate through the rest of the items. For each, if it’s bigger than the max-so-far, replace the accumulator variable’s value with the value of the current item.

Step through the execution of this code to get a feel for how it works.


Now, you may notice that this code will break if there isn’t more than one item in L. You would get an error on line 4 for trying to access item L[1], which is the second item. If we assume that L will have only numbers >= 0, we can initialize the max-so-far to be 0 and loop through all of the items in L.


We can do a similar thing with a dictionary to find the maximum value. You can loop through the keys and replace the max-so-far whenever the current key’s associated value is greater than the max-so-far.

Check your understanding

Next Section - Accumulating the Best Key