![]() |
VOOZH | about |
Lists in Python have various built-in methods to remove items such as remove, pop, del and clear methods. Removing elements from a list can be done in various ways depending on whether we want to remove based on the value of the element or index.
The simplest way to remove an element from a list by its value is by using the remove()method. Here's an example:
[10, 20, 40, 50]
Let's us see different method to remove elements from the list.
Table of Content
Theremove() method deletes the first occurrence of a specified value in the list. If multiple items have the same value, only the first match is removed.
[10, 30, 20, 40, 50]
The pop() method can be used to remove an element from a list based on its index and it also returns the removed element. This method is helpful when we need to both remove and access the item at a specific position.
[10, 30, 40, 50] Removed Item: 20
If we do not specify the index then pop() method removes the last element.
[10, 20, 30, 40] Removed Item: 50
The del statement can remove elements from a list by specifying their index or a range of indices.
[10, 20, 40, 50]
We can also use del to remove multiple elements from a list by specifying a range of indices.
[10, 50, 60, 70]
If we want to remove all elements from a list then we can use the clear() method. This is useful when we want to empty a list entirely but keep the list object.