5.0 Python: Remove List Items
5.1 Remove Specified Item
The remove()
method removes the specified item.
5.1.1 Example
Remove "banana"
:
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
note
If there are more than one item with the specified value, the remove()
method removes the first occurrence:
5.1.2 Example
Remove the first occurrence of "banana"
:
thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
thislist.remove("banana")
print(thislist)
5.2 Remove Specified Index
The pop()
method removes the specified index.
5.2.1 Example
Remove the second item:
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
note
If you do not specify the index, the pop()
method removes the last item.
5.2.2 Example
Remove the last item:
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
The del
keyword also removes the specified index:
5.2.3 Example
Remove the first item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
5.2.4 Example
Delete the entire list:
thislist = ["apple", "banana", "cherry"]
del thislist
5.3 Clear the List
The clear()
method empties the list.
The list still remains, but it has no content.
5.3.1 Example
Clear the list content:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)