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
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.
newList is [10,20,30] and item is 40, then newList becomes [10,20,30,40] newList is ['AZ',CA','OR'] and item is 'NV'then newList becomes ['AZ','CA','OR','NV']
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:
newList [10,20,30] and item 40, you'll get unsupported operation list + int newList ['AZ','CA','OR'] and item 'NV' you'll get unsupported operation list + str 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).
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:
newList is [10,20,30] and item is 40, then newList becomes [10,20,30,[40]] newList is ['AZ',CA','OR'] and item is 'NV'then newList becomes ['AZ','CA','OR',['NV']]That is, in both cases, the new item is a "list inside a list"—a list containing a single item.
To understand the difference:
40 out of [10,20,30,40] we use newList[3]40 out of [10,20,30[40]] we have to use newList[3][0]newList is ['AZ','CA','OR','NV'] we use newList[3][1]newList is ['AZ','CA','OR',['NV']] we use newList[3][1][0]