Remove List Items
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 item at that specified index.
Example 1:
Output:
Example 2:
Output:
What if you want to remove a specific item from the list?
remove():
This method removes specific item from the list.
Example:
Output:
del:
del is not a method, rather it is a keyword which deletes item at specific from the list, or deletes the list entirely.
Example 1:
Output:
Example 2:
Output:
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:
Output: