Delete a list element by value in Python
Problem description
How to delete a list element by its value without knowing its possition?
Problem solution
There is a Python's remove() method for list manipulation which allows you to delete a list element without knowing its index. All you need is element's value. For example:
thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
thislist.remove("cherry")
print(thislist) # output: ["apple", "banana", "banana", "kiwi"]
But what if there are two elements with same value?
thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
thislist.remove("banana")
print(thislist) # output: ["apple", "cherry", "banana", "kiwi"]
remove() method removes the first occurrence item with the specyfic value.
And what if there aren't any elements with given value?
thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
thislist.remove("oranges") # throws ValueError
What if you want to delete all of elements with specific value? You can rebuild your list without those element, check this:
thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
thislist = [element for element in thislist if element != 'banana'] # rebuild the list
print(thislist) # output: ['apple', 'cherry', 'kiwi']