In this post, you will learn How to remove an item by value from a list.
remove in python –
Sometimes you don’t know the index of the item that you want to delete from the list. But if you know the value of the item that you want to delete then you can use the remove method in python.
Syntax of remove in List-
The remove method in list takes a single argument the value that you want to remove from the list.
Remove an Item from The List –
Let’s say that you want to remove Facebook from the list of companies.
In : companies = ['Google','Apple','Microsoft','Netflix', 'Facebook'] In : companies.remove('Facebook') In : companies Out: ['Google', 'Apple', 'Microsoft', 'Netflix']
Remove from list when duplicate item exists –
If you list contains duplicate items, then remove will only delete the first item from the list and leave the remaining as it is.
In : fruits = ['Mango','Apple','Apple','Apple','Banana'] In : fruits.remove('Apple') In : fruits Out: ['Mango', 'Apple', 'Apple', 'Banana']