☰ Year plan · Communication Technology

Lists

Week 7 · Unit 1, Lesson 3 Strings and Lists in Python (2) · 3 lessons
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.

AB
1After the linenumbers
2numbers = [5, 9][5, 9]
3numbers.append(2)[5, 9, 2]
4numbers.remove(5)[9, 2]
5numbers[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
Omar adds Sami to the list, removes Omar, and then prints the names with a loop. The printed list after each change shows what happened.
Python
1names = ["Mona", "Sami"]
2names.remove("Adam")
Output
ValueError: the value is not in the list
Removing a value that is not in the list is an error. The list has no Adam, so Python stops with a ValueError.
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
What does remove(5) delete from [5, 9, 5]?
3
Does remove take a value or a position?
4
How many times does for name in names run for a list of 4 names?