Python (Scripting) - Remove elements from a list

by
Jeremy Canfield |
Updated: February 11 2024
| Python (Scripting) articles
Let's say you have a list of fruit. remove can be used to remove a single element from the list.
#!/usr/bin/python3
fruits = ["apple", "banana", "pineapple", "grapes", "apple"]
print(f"fruits before remove = {fruits}")
fruits.remove("banana")
print(f"fruits after remove = {fruits}")
Which should return the following.
fruits before remove = ['apple', 'banana', 'pineapple', 'grapes', 'apple']
fruits after remove = ['apple', 'pineapple', 'grapes', 'apple']
If you try to remove an element that is not in the list.
#!/usr/bin/python3
fruits = ["apple", "banana", "pineapple", "grapes", "apple"]
fruits.remove("peach")
An exception will be raised.
Traceback (most recent call last):
File "/home/john.doe/demo.py", line 4, in <module>
fruits.remove("peach")
ValueError: list.remove(x): x not in list
For this reason, I almost always use an if statement to only attempt the removal if the element is in the list.
#!/usr/bin/python3
fruits = ["apple", "banana", "pineapple", "grapes", "apple"]
if "peach" in fruits:
fruits.remove("peach")
It is important to recongize that remove will only remove the first matching element from the list.
#!/usr/bin/python3
fruits = ["apple", "banana", "pineapple", "grapes", "apple"]
print(f"fruits before remove = {fruits}")
fruits.remove("apple")
print(f"fruits after remove = {fruits}")
In the above example, only the first occurrence of "apple" is removed from the list.
fruits before remove = ['apple', 'banana', 'pineapple', 'grapes', 'apple']
fruits after remove = ['banana', 'pineapple', 'grapes', 'apple']
Here is how you can remove every occurrence of a string from a list.
#!/usr/bin/python3
fruits = ["apple", "banana", "apple", "grapes"]
string_to_remove = ["apple"]
fruits = list(set(fruits) - set(string_to_remove))
print(f"fruits = {fruits}")
Which should return the following now.
fruits = ['banana', 'grapes']
Did you find this article helpful?
If so, consider buying me a coffee over at