Learning objectives
By the end of this section you should be able to
- Modify a list using
append()
,remove()
, andpop()
list operations. - Search a list using a
for
loop.
Using list operations to modify a list
An append()
operation is used to add an element to the end of a list. In programming, append means add to the end. A remove()
operation removes the specified element from a list. A pop()
operation removes the last item of a list.
Example 9.1
Simple operations to modify a list
The code below demonstrates simple operations for modifying a list.
Line 8 shows the append()
operation, line 12 shows the remove()
operation, and line 17 shows the pop()
operation. Since the pop()
operation removes the last element, no parameter is needed.
1 | """Operations for adding and removing elements from a list.""" |
2 | |
3 | # Create a list of students working on a project |
4 | student_list = ["Jamie", "Vicky", "DeShawn", "Tae"] |
5 | print(student_list) |
6 | |
7 | # Another student joins the project. The student must be added to the list. |
8 | student_list.append("Ming") |
9 | print(student_list) |
10 | |
11 | # "Jamie" withdraws from the project. Jamie must be removed from the list. |
12 | student_list.remove("Jamie") |
13 | print(student_list) |
14 | |
15 | # Suppose "Ming" had to be removed from the list. |
16 | # A pop() operation can be used since Ming is last in the list. |
17 | student_list.pop() |
18 | print(student_list) |
The above code's output is:
['Jamie', 'Vicky', 'DeShawn', 'Tae'] ['Jamie', 'Vicky', 'DeShawn', 'Tae', 'Ming'] ['Vicky', 'DeShawn', 'Tae', 'Ming'] ['Vicky', 'DeShawn', 'Tae']
Concepts in Practice
Modifying lists
Iterating lists
An iterative for loop can be used to iterate through a list. Alternatively, lists can be iterated using list indexes with a counting for loop. The animation below shows both ways of iterating a list.
Concepts in Practice
Iterating lists
For the following questions, consider the list:
my_list = [2, 3, 5, 7, 9]
Try It
Sports list
Create a list of sports played on a college campus. The sports to be included are baseball, football, tennis, and table tennis.
Next, add volleyball to the list.
Next, remove "football"
from the list and add "soccer"
to the list.
Show the list contents after each modification.
Try It
Simple Searching
Write a program that prints "found!"
if "soccer"
is found in the given list.