Guide to Remove an Element From a List in Python
A Python list can contain multiple elements in sequential order, and each element has a unique index number, which can be used to access that element. A list in Python has many methods associated with it, and there are some particular methods that can be used to remove a specific element from a Python list.
In this tutorial, we have mentioned the various methods that you can use to remove elements from a list in Python. By the end of this tutorial, you will be able to decide when to use which method to remove an element from a list in Python.
Remove an Element from a List in Python
The remove() Method
remove()
is the list method that can remove a specific element from the list. It accepts the element value as a parameter and removes that element. It returns a None value, and if we try to remove a value that is not present in the list, then it throws an error.
Example
my_list = ["hello", "world", "welcome", "to", "techgeekbuzz"]
# removing a specific element.
my_list.remove("to")
print(my_list)
Output
['hello', 'world', 'welcome', 'techgeekbuzz']
Example 2
#removing an element that is not present in the list.
my_list = ["hello", "world", "welcome", "to", "techgeekbuzz"]
my_list.remove("too")
print(my_list)
Output
Traceback (most recent call last):
File "listexample.py", line 3, in <module>
my_list.remove("to0")
ValueError: list.remove(x): x not in list
2. The clear() Method
Another way to remove an element from a list in Python is by using the clear()
method. It is a list method that can remove all the elements present in the list. We can use this method when we want to remove all the list elements at once. Similar to the remove() method, it returns a None value.
Example
my_list = [1,2,3,4,5,6,7]
# remove all elemets from the list
my_list.clear()
print(my_list)
Output
[]
3. The pop() Method
my_list = ["hello", "world", "welcome", "to", "techgeekbuzz"]
# removing the last element from the list.
popped = my_list.pop()
print("The poped element is:", popped)
print("Now the list is:",my_list)
Output
The popped element is: techgeekbuzz
Now the list is: ['hello', 'world', 'welcome', 'to']
Example 2
my_list = ["hello", "world", "welcome", "to", "techgeekbuzz"]
# removing a specific element using the index value.
popped = my_list.pop(2)
print("The poped element is:", popped)
print("Now the list is:",my_list)
Output
The popped element is: welcome
Now the list is: ['hello', 'world', 'to', 'techgeekbuzz']
Summary
- If we know the value of the element to be removed, then we should use the remove() method.
- If we want to remove all the elements from the list, then we can use the list clear() method or the del keyword with list slicing.