Python Tutorial
Delete/Remove Elements From Python List
How to Delete or Remove Elements From a List in Python?
There are two main ways to remove elements from a Python list. We have discussed both ways below with examples:
1. Using pop() function in Python
The pop()
method is used to remove & return an element from a set. By default, it merely eliminates the last element. It provides the element's index as an input to the pop()
function to remove an element from a specific point in the List.
Example:
Remove the last item:
thislist = ["pear", "melon", "orange"]
thislist.pop()
print(thislist)
Output
['pear', 'melon']
2. Using remove() function in Python
The built-in remove()
function in Python can be used to remove elements from the list, however, if the element doesn't exist in the set, an error will occur.
The Remove()
method in Python only removes one element at a time; the iterator is used to remove a range of elements. Removes the provided object with the remove()
function.
Example
Remove "melon":
thislist = ["pear", "melon", "orange"]
thislist.remove("melon")
print(thislist)
Output
['pear', 'orange']