More on lists#
This section covers some more operations on lists. See lists for an introduction to lists.
Removing values from a list#
Another common operation on lists, is finding and removing values.
Removing values by index#
The pop
method of a list, removes a value at a given position in the list, and returns that value.
my_list = [9, 10, 3, 0]
my_list
[9, 10, 3, 0]
By default, with no arguments, it removes and returns the last value in the list:
last_value = my_list.pop()
last_value
0
The list has lost the last value.
my_list
[9, 10, 3]
You can give pop
an argument, which is the position from which you want to
get the value. pop
removes the element at that position, shortening the
list by one element.
mid_value = my_list.pop(1)
mid_value
10
my_list
[9, 3]
Removing values by finding#
Sometimes we want to remove a certain specific value from the list.
For example, let’s say I have this list:
my_list = [9, 10, 999, 0]
I realize that I don’t want the 999 value. I can remove
it, using the remove
method of the list:
my_list.remove(999)
This modifies my list:
my_list
[9, 10, 0]
What happens if I have more than one value that matches my argument to remove
?
my_list = [9, 10, 999, 0, 999]
my_list.remove(999)
We lost the first value that matches:
my_list
[9, 10, 0, 999]
Counting number of occurrences in a list#
The count
method of the list counts the number of occurrences of
a particular value. The argument to the count
method is the value you want
to check for.
my_list = [9, 10, 999, 0, 999]
my_list.count(999)
2
Now we remove one of the 999 values, and count again:
my_list.remove(999)
my_list
[9, 10, 0, 999]
my_list.count(999)
1