You already know how to append and insert elements to list. You also know how to extend lists. Today we’ll learn how to remove elements from a list.
Here’s the video version of this article:
You can use the del statement to remove an element from a list. You just need to know the index of the element you want to remove:
>>> days = ["Monday", "Friday", "Saturday"]
>>> del days[1]
>>> days
['Monday', 'Saturday']
We can also combine the del statement with slicing to remove more elements:
>>> numbers = [4, 2, 6, 7, 16, 41, 54, 84, 21]
>>> del numbers[3:7]
>>> numbers
[4, 2, 6, 84, 21]
You can also use the del statement to remove the whole list:
>>> numbers = [4, 2, 6, 7, 16, 41, 54, 84, 21]
>>> del numbers
Now the list doesn’t exist anymore, that’s why we’re getting an error when trying to echo it:
>>> numbers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'numbers' is not defined
You can use the method remove(x) to remove elements if you don’t know the index:
>>> days = ["Monday", "Friday", "Saturday"]
>>> days.remove("Friday")
>>> days
['Monday', 'Saturday']
The remove(x) method removes the first occurrence of x.
>>> scores = [20, 10, 20, 50, 70, 40]
>>> scores.remove(20)
>>> scores
[10, 20, 50, 70, 40]
>>> scores.remove(20)
>>> scores
[10, 50, 70, 40]
If the element is not found, we get an error:
>>> scores.remove(20)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
You can remove all the elements from a list either by using the del statement or by using the clear method. Suppose we have the following list:
>>> animals = ["tortoise", "reindeer", "rattlesnake"]
We can remove all the elements of the list, but not the list itself, using the del statement and slicing:
>>> del animals[:]
>>> animals
[]
Alternatively, we can use the clear method:
>>> animals = ["tortoise", "reindeer", "rattlesnake"]
>>> animals.clear()
>>> animals
[]