15.5. Adding and Removing Items

Sometimes, we do not know all of the items in a list in advance - we want to build up A list as the program is running. To do this, we can start with a blank list using [] as our list. And then we can use append to add things to the end of the list.

This program adds two strings to the list words. Add code to add the word “Carrot” to the list after “Banana” but before “Date”

It is also possible to add items to locations other than the end of the list by using the insert function. To use it, we provide an index of where to insert the new value with the value we want to insert. Try running this sample with codelens:

To remove items from a list, there are two main options:

This sample shows all three methods:

Activity: CodeLens 15.5.4 (cspcollectionsintro_addremove4)

We want the list called alphabet to contain the letters “A”, “B”, “C”, “D” in that order. Use a combination of append, insert, remove, and pop to make it have the right values.

(Do not use letters[index] to change the existing items.)

The following program should make the discounts list contain the values of all the items from price_list after they have been discounted by 50%. To do so, we need to loop through the original prices, calculate the discounted price, then append it to the discount list.

Put the blocks in the right order and indent them correctly. There are some blocks you will not use.

You have attempted of activities on this page