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 some particular methods can be used to remove a specific element from a Python list. In this tutorial, we have mentioned the various ways 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.
How to Remove an Element from a List in Python?
1. 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, it throws an error.
Example
Output
Example
Output
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
Output
3. The pop() Method
pop() is a list method that is generally used to remove the last element from the list. However, we can also specify the index value to remove a specific element from the Python list. Unlike the above two methods, it returns the element that has been removed.
Example 1
Output
Example 2
Output
How to Remove an Element from a List in Python using del keyword
del
is a Python keyword that can delete objects. Using the del keyword, we can either completely delete the list object or remove some specific elements.
How to Remove specific elements from a list in Python
Output
How to Delete the entire list in Python
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.
- We can remove the last element or a specific element (index value required) of a list using the pop() method.
People are also reading:
Leave a Comment on this Post