Skip to main content

Section 9.2 The Accumulator Pattern with Lists

On the preceding page, we added all the items in the list to the accumulator. Sometimes when we’re accumulating, we don’t want to add to our accumulator every time we iterate. Consider, for example, the following program which counts the number of names with more than 3 letters.
Here, we initialize the accumulator variable to be zero on line 1.
We iterate through the sequence (line 2).
The update step happens in two parts. First, we check to see if the name is longer than 3 letters. If so, then we increment the accumulator variable long_names (on line 4) by adding one to it.
At the end, we have accumulated the total number of long names.
We can use conditionals to also count if particular items are in a string or list. The following code finds all occurrences of vowels in a string.

Subsection 9.2.1 Accumulating the Maximum Value

We can also use the accumulation pattern with conditionals to find the maximum or minimum value. Instead of continuing to build up the accumulator value like we have when counting or finding a sum, we can reassign the accumulator variable to a different value.
The following example shows how we can get the maximum value from a list of integers.
Here, we initialize biggest_num to the first element in our list. Why didn’t we set it to zero? Because we cannot assume that there will never be any negative numbers in the list. By assigning nums[0] to biggest_num, we are at least guaranteed that the result of our program will be one of the items in the list.
In the for loop, we check to see if the current value of n is greater than the current value of biggest_num. If it is, then we want to update biggest_num so that it now is assigned the higher number. Otherwise, we do nothing and continue the for loop.

Subsection 9.2.2 Accumulating a String Result

The accumulator pattern can be used to convert a list of items to a string.
Consider the following program:
Here, the accumulator variable is result. Each time through the loop, the program concatenates the current contents of result with the comma separator and a score from the list, and updates the result with the new value. Use CodeLens to step through this example to see it in action.
The output of the program has some undesirable formatting problems: there is a trailing comma instead of a period, and there are no spaces between the items. The next activity lets you work to correct those problems.

Checkpoint 9.2.1.

Let’s work to improve the formatting of the sentence produced by the program above. Revise the following code so that it outputs the sentence:
The scores are 85, 95, and 70.
Hint.
Try changing the loop so that it does not process the final score. Handle that last score separately, after the loop finishes.
Solution.
This solution works by iterating over all of the scores in the list except the last, and dealing with that one separately.
scores = [85, 95, 70]
result = ''
for score in scores[:-1]:
   result = result + str(score) + ', '

# Now, append the last score
result = result + 'and ' + str(scores[-1]) + '.'

print("The scores are " + result)

Checkpoint 9.2.2.

    What is printed by the following statements?
    s = "We are learning!"
    x = 0
    for char in s:
        if char in 'abcde':
            x = x + 1
    print(x)
    
  • 2
  • Though only two of the letters in the list are found, we count them each time they appear.
  • 5
  • Yes, we add to x each time we come across a letter in the list.
  • 0
  • Check again what the conditional is evaluating. The value of ch will be a character in the string s, so what will happen in the if statement?
  • There is an error in the code so it cannot run.
  • There are no errors in this code.

Checkpoint 9.2.3.

    What is printed by the following statements?
    my_list= [5, 2, 1, 4, 9, 10]
    min_value = 0
    for item in my_list:
       if item < min_value:
           min_value = item
    print(min_value)
    
  • 10
  • Not quite. What is the conditional checking?
  • 1
  • min_value was set to a number that was smaller than any of the numbers in the list, so it was never updated in the for loop.
  • 0
  • Yes, min_value was set to a number that was smaller than any of the numbers in the list, so it was never updated in the for loop.
  • There is an error in the code so it cannot run.
  • The code does not have an error that would prevent it from running.

Checkpoint 9.2.4.

Challenge For each word in words, add ‘d’ to the end of the word if the word ends in “e” to make it past tense. Otherwise, add ‘ed’ to make it past tense. Save these past tense words to a list called past_tense.
Now that we have finished our in-depth review of the accumulator pattern, let’s look at lists in detail, first describing the things they have in common with strings.