9.1 Modifying and iterating lists
Learning objectives
By the end of this section you should be able to
Modify a list using append, remove, and pop 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 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.
"""Operations for adding and removing elements from a list."""
# Create a list of students working on a project
student_list = ["Jamie", "Vicky", "DeShawn", "Tae"]
print(student_list)
# Another student joins the project. The student must be added to the list.
student_list.append("Ming")
print(student_list)
# "Jamie" withdraws from the project. Jamie must be removed from the list.
student_list.remove("Jamie")
print(student_list)
# Suppose "Ming" had to be removed from the list.
# A pop() operation can be used since Ming is last in the list.
student_list.pop()
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']
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.
Note
Iterating lists
For the following questions, consider the list:
my_list = [2, 3, 5, 7, 9]
Note
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.
Note
Simple Searching
Write a program that prints "found!" if "soccer" is found in the given list.
sport_list = ["Tennis", "Baseball", "Basketball", "Soccer", "Table Tennis"]