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:
- The item just does not get added
- Try it!
- There is an error and the program stops
- Try it!
- The item is added to the end of the list
- Correct
- The list is extended to be long enough that there is an item index 200
- Try it!
What happens if you use an index that does not exist to insert at? Change the last insert in the sample above to insert at location 200 instead of 2. What happens?
To remove items from a list, there are two main options:
pop()
removes an item from the end of a list. (It “pops” the item off.)pop(index)
removes an item from the specified index.remove(value)
removes the first copy of the specified value from the list.
This sample shows all three methods:
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.