Remove List Items
There are various methods to remove items from the list: pop()
, remove()
, del
, clear()
pop():
This method removes the last item of the list if no index is provided. If an index is provided, then it removes the item at that specified index.
Example 1:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
colors.pop() # removes the last item of the list
print(colors)
Output:
['Red', 'Green', 'Blue', 'Yellow']
Example 2:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
colors.pop(1) # removes item at index 1
print(colors)
Output:
['Red', 'Blue', 'Yellow', 'Green']
What if you want to remove a specific item from the list?
remove():
This method removes a specific item from the list.
Example:
colors = ["voilet", "indigo", "blue", "green", "yellow"]
colors.remove("blue")
print(colors)
Output:
['voilet', 'indigo', 'green', 'yellow']
del:
del
is not a method, rather it is a keyword which deletes an item at a specific index from the list, or deletes the list entirely.
Example 1:
colors = ["voilet", "indigo", "blue", "green", "yellow"]
del colors[3]
print(colors)
Output:
['voilet', 'indigo', 'blue', 'yellow']
Example 2:
colors = ["voilet", "indigo", "blue", "green", "yellow"]
del colors
print(colors)
Output:
NameError: name 'colors' is not defined
We get an error because our entire list has been deleted and there is no variable called colors
which contains a list.
What if we don’t want to delete the entire list, we just want to delete all items within that list?
clear():
This method clears all items in the list and prints an empty list.
Example:
colors = ["voilet", "indigo", "blue", "green", "yellow"]
colors.clear()
print(colors)
Output:
[]