2
Adding, removing and looping over a list
ICT Prep 3 Term 1, Unit 1, Lesson 3: pp. 34–42
GoalAdd and remove items with append and remove, loop over a list and predict the list after changes.
New words
append() · adds an item at the end of the listremove() · deletes the first item equal to the given valuefor item in list · a loop that visits every item in orderValueError · shown when remove() cannot find the value
Explanation
A list can grow and shrink. names.append("Sami") adds Sami at the end. names.remove("Omar") deletes the first item equal to Omar. Notice that remove takes the value, not the position. If the value is not in the list, Python stops with a ValueError. A loop visits all the items: for name in names runs once for each item, in order. To predict the result of several changes, write the list again after every line, as in the sheet. This is the same trace habit you used in Week 3 for the loop.
| A | B | |
|---|---|---|
| 1 | After the line | numbers |
| 2 | numbers = [5, 9] | [5, 9] |
| 3 | numbers.append(2) | [5, 9, 2] |
| 4 | numbers.remove(5) | [9, 2] |
| 5 | numbers[0] = 1 | [1, 2] |
Worked examples
Python
1names = ["Mona", "Omar"] 2names.append("Sami") 3print(names) 4names.remove("Omar") 5print(names) 6for name in names: 7 print(name)
Output
['Mona', 'Omar', 'Sami'] ['Mona', 'Sami'] Mona Sami
Python
1names = ["Mona", "Sami"] 2names.remove("Adam")
Output
ValueError: the value is not in the list
Class activity
Start with the list [3, 6, 9]. On paper apply: append(12), remove(6), then change the first item to 1. Write the list after every step. Then write the line that would cause a ValueError.
Practice
1
What is the list after numbers = [2, 4] and numbers.append(6)?
[2, 4, 6].
2
What does remove(5) delete from [5, 9, 5]?
Only the first 5, so the list becomes [9, 5].
3
Does remove take a value or a position?
A value.
4
How many times does for name in names run for a list of 4 names?
Four times, once for each item.