In this article, we would cover how to delete an element from list in Python. As we already know, lists in Python are mutable. That is, we can modify the elements of a list. This is different from tuples where the sequence can’t be modified.
We can use lists and tuples as per our requirements. So, if someone wants a fixed sequence. Then, opt for tuple. Otherwise, go with lists.
There are four methods we would cover –
- remove(),
- pop(),
- clear() and,
- del().
Delete an element from list in Python
Deleting an element from list is pretty easy. Let’s say we have a list, x –
Method I. remove() method
x=["a","b","c","d"]
To remove a specific item –
x.remove("b")
And, to print the outcome –
print(x)
This would return with –
['a', 'c', 'd']
With remove(), we need to provide the specific item name which we want to remove.
Method II. pop() method
x=["a","b","c","d"]
There are two options we have got here.
A. Remove an item at a specific index –
x.pop(2) print(x)
It would return with –
'c' ['a', 'b', 'd']
Clearly, it has removed the item at index 2, which is “c”.
B. If we don’t provide the index number, It removes the last item by default.
x=["a","b","c","d"] x.pop() print(x)
Output –
'd' ['a', 'b', 'c']
Method III. clear() method
With clear() method, we don’t get the option to keep some items and delete others. Using this would leave the entire list empty.
x=["a","b","c","d"] x.clear() print(x)
Output –
[ ]
Method IV. del statement
With del statement, we can either delete an item at a specific index or completely delete the list itself.
A. For item at specific index –
x=["a","b","c","d"] del x[2] print(x)
It will return with –
['a', 'b', 'd']
It deleted the third item or item at index number 2.
B. To delete the list itself –
x=["a","b","c","d"] del x print(x)
The output of print() would be –
NameError: name 'x' is not defined
It shows not defined error because our list is gone.
In conclusion, we have discussed how to delete an item from the list in Python using four methods – del, pop, remove and clear. Choose the method as per you requirements.