Removing Items from a List in Python: Using the Remove Method
Learn how to remove specific items from a Python list using the remove()
method. This guide provides a practical example of how to delete an item from a list and see the updated list. Understand the syntax and application of the remove()
method to manage list contents effectively.
Python - Remove List Items
Remove Specified Item
The remove()
method removes the specified item from the
list.
Example
Remove "banana":
mylist = ["grape", "banana", "kiwi"]
mylist.remove("banana")
print(mylist)
Output
["grape", "kiwi"]
If there are multiple items with the specified value, the
remove()
method removes the first occurrence:
Example
Remove the first occurrence of "banana":
mylist = ["grape", "banana", "kiwi", "banana", "melon"]
mylist.remove("banana")
print(mylist)
Output
["grape", "kiwi", "banana", "melon"]
Remove Specified Index
The pop()
method removes the item at the specified index.
Example
Remove the second item:
mylist = ["grape", "banana", "kiwi"]
mylist.pop(1)
print(mylist)
Output
["grape", "kiwi"]
If you do not specify the index, the pop()
method removes
the last item.
Example
Remove the last item:
mylist = ["grape", "banana", "kiwi"]
mylist.pop()
print(mylist)
Output
["grape", "banana"]
Remove Specified Index with del
Keyword
The del
keyword also removes the item at the specified
index.
Example
Remove the first item:
mylist = ["grape", "banana", "kiwi"]
del mylist[0]
print(mylist)
Output
["banana", "kiwi"]
The del
keyword can also delete the list entirely.
Example
Delete the entire list:
mylist = ["grape", "banana", "kiwi"]
del (mylist)
Clear the List
The clear()
method empties the list, but the list itself
remains.
Example
Clear the list content:
mylist = ["grape", "banana", "kiwi"]
mylist.clear()
print(mylist)
Output
[]