List methods in Python allow us to modify list objects.
Most list methods modify the original list and return None. Lists are mutable so they can be modified in-place.
The list below is assigned to the variable name
math_grades and contains a collection of scores for math exams for a single student.
There are 4 items in the list below.
math_grades = [88, 91, 82, 84]
We can add a new item by calling the
append method on our list and include an argument for a value to add.
We can add a 5th score of 100.
[88, 91, 82, 84, 100]
extend method in Python to add multiple items in one call.
The argument passed to
extend should be an iterable. In the example below, it's a list of letter grades.
[88, 91, 82, 84, 100, 'A', 'B+']
Let's say we forgot to include that student's first math exam score in
math_grades. Since the order of elements in a list matters, we want to make sure we add their first score to be the first element in the list.
We can use the
insert method to insert an item at any position in a list.
We want to insert a score of
99 at index
0. Our first argument is the index of the item and second argument is item's value.
[99, 88, 91, 82, 84, 100, 'A', 'B+']
99 to the beginning of
math_grades, all items increased their index value by 1.
Let's say, as the teacher, we found an error in the 2nd math exam and therefore we want to remove the score from the student's
We can call the
pop method and pass in the index of the list item to remove.
We want to remove the score of
88 at index
pop method returns the item from the list.
We can verify the
88 was removed.
[99, 91, 82, 84, 100, 'A', 'B+']
You can also remove an item from a list given the item's value. You don't need to know its index.
To remove an item, call the
remove method and pass in an item's value.
Let's remove the score of
[99, 91, 82, 84, 'A', 'B+']