9.10. The Accumulator Pattern with Lists

We can accumulate values into a list rather than accumulating a single numeric value. Consider, for example, the following program which transforms a list into a new list by squaring each of the values.

Here, we initialize the accumulator variable to be an empty list, on line 2.

We iterate through the sequence (line 3). On each iteration we transform the item by squaring it (line 4).

The update step appends the new item to the list which is stored in the accumulator variable (line 5). The update happens using the .append(), which mutates the list rather than using a reassignment. Instead, we could have written accum = accum + [x], or accum += [x]. In either case, we’d need to concatenate a list containing x, not just x itself.

At the end, we have accumulated a new list of the same length as the original, but with each item transformed into a new item. This is called a mapping operation, and we will revisit it in a later chapter.

Note how this differs from mutating the original list, as you saw in a previous section.

Check your understanding

    seqmut-9-1: What is printed by the following statements?

    alist = [4,2,8,6,5]
    blist = [ ]
    for item in alist:
       blist.append(item+5)
    print(blist)
    
  • [4,2,8,6,5]
  • 5 is added to each item before the append is performed.
  • [4,2,8,6,5,5]
  • There are too many items in this list. Only 5 append operations are performed.
  • [9,7,13,11,10]
  • Yes, the for loop processes each item of the list. 5 is added before it is appended to blist.
  • Error, you cannot concatenate inside an append.
  • 5 is added to each item before the append operation is performed.

    seqmut-9-2: What is printed by the following statements?

    list= [3,0,9,4,1,7]
    new_list=[]
    for i in range(len(list)):
       new_list.append(list[i]+5)
    print(new_list)
    
  • [8,5,14,9,6]
  • 5 is added to each list[i] before the append is performed.
  • [8,5,14,9,6,12]
  • Yes, the for loop processes each list[i] of the list. 5 is added before list[i] is appended to blist.
  • [3,0,9,4,1,7,5]
  • There are too many items in this list. Only 5 append operations are performed.
  • Error, you cannot concatenate inside an append.
  • 5 is added to each list[i] before the append operation is performed.
  1. For each word in the list verbs, add an -ing ending. Save this new list in a new list, ing.
Given the list of numbers, numbs, create a new list of those same numbers increased by 5. Save this new list to the variable newlist.
Challenge Now do the same as in the previous problem, but do not create a new list. Overwrite the list numbs so that each of the original numbers are increased by 5.
For each number in lst_nums, multiply that number by 2 and append it to a new list called larger_nums.
Next Section - 9.11. The Accumulator Pattern with Strings