While delete an item from a list in python occurred in 4 ways:
- remove()
pop()
- del
- clear()
Remove Method:
The remove() method removes the specified item.
#Example => Remove "banana": thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist) #Output ['apple', 'cherry']
Remove Specified Index:
Here the pop method removes the specified index.
#Example => Remove the second item: thislist = ["apple", "banana", "cherry"] thislist.pop(1) print(thislist) #Output ['apple', 'cherry']
If you do not specify the index, the pop()
method removes the last item.
#Example => Remove the last item: thislist = ["apple", "banana", "cherry"] thislist.pop() print(thislist) #Output ['apple', 'banana']
There is another keyword called del to remove the specified index:
#Example: Remove the first item thislist = ["apple", "banana", "cherry"] del thislist[0] print(thislist) #Output ['banana', 'cherry']
Clear the list:
The clear()
method delete all the items inside the list.
But at the end the list is present with no content.
#Example => Clear the list content: thislist = ["apple", "banana", "cherry"] thislist.clear() print(thislist) #Output: []
Please write comments or WhatsApp if you find anything incorrect, or you want to share more information about this topic discussed above.