It may be stretching things a bit to say that the minimum of a list, or the maximum, can be found by accumulation. After all, what is being accumulated? Informally, what each iteration is accumulating is the knowlege of all the previously seen items in the sequence. Initially, there is no knowledge. When the loop finishes all iterations, there is complete knowledge of the sequence.

The most difficult step for a beginner is to think of a useful meaning for an accumulation variable. The accumulation variable should have three properties:

  1. The initial value of the accumulation variable should be assigned, before the loop, to be something that would make sense if the list (or sequence) happens to be empty or happens to have only one item. Thus, in the case of a sum (adding up all the items), the value would be zero -- that would work even if the sequence has one item, because adding zero to the first item gets the correct result.

  2. The initial value of the accumulation variable should be something that can be improved in each iteration of the loop that finds some better knowledge (due to the item it sees). So, for finding the minimum, the ideal value would be infinity: every item in any Python sequence is less than infinity --- hence each item is an improvement compared to infinity. As the chapter points out, we cannot assign infinity in Python, so something else is needed.

  3. If we consider only the first n items in a sequence, then the value of the accumulation variable should be the correct result after n iterations of the loop.

As an example, let S be a list of character strings, and the problem is to define a function minstring(S) that returns the minimum-length string in S. What would be a reasonable choice for the accumulation variable? If S is an empty list, there is no clear choice of what the answer should be, so as a backup plan, we follow the idea of the chapter and pick S[0] as the initial value of the accumulation variable

1
2
3
4
5
6
def minstring(S):
  Accum = S[0]  # initial choice of shortest string
  for item in S:
     if len(item) < len(Accum):  # improvement?
        Accum = item
  return Accum

Notice how, in each iteration of the loop, the variable Accum will be the shortest word found so far (except in case of a tie, in which case Accum will be the first word found with the same short length).