CS8, UCSB
Accmulating a List in Python

Return to CS8 home page

Accumulator with numbers: the right way

When using the accumulator pattern to add numbers, we initialize the total to zero:

total = 0

then we add the new item into the total in one of two ways:

total = total + item

or

total += item

Accumulator with lists: the right way

With lists, we initialize the list to the empty list:

newList = []

Then, we have several correct choices for how to add item to the list

newList = newList + [ item ]
newList += [ item ]
newList.append(item)

All of those are correct.

 

Accumulator pattern on lists: the wrong ways

Wrong way #1: Using + when both sides are not lists

newList = newList + item     # wrong! should benewList = newList + [ item ]
newList += item              # wrong! should be newList += [ item]  

In both cases, the error will be that the operand + is not supported:

Wrong way #2: Thinking that append returns a result

newList = newList.append(item)    # wrong! should be newList.append(item)  

You won't get an error reported by Python, but newList will be set to None instead of the result you want. The append method does not return a value—it directly modifies the object it is called on (the one that appears on the left hand side of the dot-operator, in this case, newList).

Wrong way #3: Extra [ ] inside argument to append

newList.append([item])    # wrong! should be newList.append(item)  

You won't get an error reported by Python, but newList will be set to something other than what you were expecting:

That is, in both cases, the new item is a "list inside a list"—a list containing a single item.

To understand the difference:




Valid XHTML 1.1 Valid CSS!