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.
Add Items¶
Add an item to the end of a list¶
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.
math_grades.append(100)
math_grades
[88, 91, 82, 84, 100]
Add multiple items to end of list¶
Use the 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.
math_grades.extend(['A', 'B+'])
math_grades
[88, 91, 82, 84, 100, 'A', 'B+']
Add item anywhere in list¶
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.
math_grades.insert(0, 99)
math_grades
[99, 88, 91, 82, 84, 100, 'A', 'B+']
In adding 99
to the beginning of math_grades
, all items increased their index value by 1.
Remove Items¶
Remove an item given an index value¶
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 math_grades
.
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 1
.
math_grades.pop(1)
88
Note the pop
method returns the item from the list.
We can verify the 88
was removed.
math_grades
[99, 91, 82, 84, 100, 'A', 'B+']
Remove an item given the item's value¶
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 100
.
math_grades.remove(100)
math_grades
[99, 91, 82, 84, 'A', 'B+']