In this Python tutorial, you will learn how to remove a specific item from a list, or remove an item at a given index from list, using list.remove() or del list[index] statements respectively.
Remove an item from Python List
You can remove or delete an object from Python List at specified position; or delete a specific object from the list.
list.remove(object)
can be used to remove a specific object from the list. remove()
removes only the first occurrence of the object in the list. Subsequent occurrences of the object remain in the list.
del list[index]
can be used to remove an object from specific index of the list.
1. Remove specific element from Python List
To remove a specific element from the list, call remove() on the list with the object passed as argument to remove().
main.py
#initialize list
aList = [True, 28, 'Tiger', 'Lion']
#remove specific item
aList.remove('Tiger')
#print list
print(aList)
Output
[True, 28, 'Lion']
The specified object is removed from the list.
Reference tutorials for the above program
2. Remove element that is not present in List
An attempt to remove a specific object from Python List, where the specified object is not present in the list, results in ValueError.
main.py
#initialize list
aList = [True, 28, 'Tiger', 'Lion']
#remove specific item
aList.remove('Rhino')
#print list
print(aList)
Output
Traceback (most recent call last):
File "main.py", line 5, in <module>
aList.remove('Rhino')
ValueError: list.remove(x): x not in list
ValueError occurs with the message list.remove(x): x not in list.
3. Remove element that has multiple occurrences in the List
In the following example, we initialize a list with an object 'Tiger'
having multiple occurrences. When we apply remove('Tiger')
on the list, only the first occurrence is removed.
main.py
#initialize list
aList = [True, 28, 'Tiger', 'Lion', 'Tiger']
#remove object
aList.remove('Tiger')
#print list
print(aList)
Output
[True, 28, 'Lion', 'Tiger']
4. Remove element from List at a specific position
To delete an object at a specific position or index from a List, use del
.
The syntax is del list[index]
.
In the following Python program, we initialize a Python list and delete an item at index 2.
main.py
#initialize list
aList = [True, 28, 'Tiger', 'Lion']
#remove item from specific position
del aList[2]
#print list
print(aList)
Output
[True, 28, 'Lion']
Conclusion
In this Python Tutorial, we learned to remove a particular object from the list or delete an item from given index of the list.