Python list remove() is a built-in function that removes an element by value in the list. It modifies the list in place, removing the first occurrence of the specified value.
stocks = ['Oracle', 'Apple', 'Nvidia'] stocks.remove('Apple') print(stocks) # Output: ['Oracle', 'Nvidia']
In this code, we are removing the stock “Apple” from the list of stocks based on its value. It does not return a new list.
Syntax
list.remove(value)
Parameters
Argument | Description |
value (required) | It represents the element that needs to be removed from the list. |
The return value of this function is None.
Removing first occurrence (Duplicates present)
If duplicate elements are present in the list, remove() will remove just the first occurrence of that element.
stocks = ['Oracle', 'Apple', 'Nvidia', 'Apple'] stocks.remove('Apple') print(stocks) # Output: ['Oracle', 'Nvidia', 'Apple']
In this code, only the first ‘Apple’ (at index 1) is removed; subsequent matches are left intact.
Removing all occurrences of a single value
If you want to remove all the occurrences of a single value, use a while loop to repeatedly call remove() until the value is no longer in the list.
stocks = ['Oracle', 'Apple', 'Nvidia', 'Apple'] value = 'Apple' while value in stocks: stocks.remove(value) print(stocks) # Output: ['Oracle', 'Nvidia']
In this code, the while loop checks if ‘Apple’ exists and removes the first occurrence each time it is found. That way, all the ‘Apple’ values from the stocks will be removed.
Remove multiple different values from the list
To remove multiple specific values, iterate over the values to remove and call the remove() method for each, handling errors if the values do not exist.
stocks = ['Oracle', 'Apple', 'Nvidia', 'Microsoft'] values_removal_list = ['Apple', 'Microsoft'] for element in values_removal_list: try: stocks.remove(element) except ValueError: pass # Skip if element not in list print(stocks) # Output: ['Oracle', 'Nvidia']
In this code, we removed two different elements, “Apple” and “Microsoft”, from the list using a for…in loop and the remove() method. It will remove only the first occurrence of each element from the list.
ValueError: list.remove(x): x not in list
If the value you are trying to remove from the list does not exist in the list, it will throw the ValueError: list.remove(x): x not in list.
stocks = ['Oracle', 'Apple', 'Nvidia'] stocks.remove('Microsoft') print(stocks) # ValueError: list.remove(x): x not in list
Empty List
If the list is empty and you try to remove any element from it, it will throw a ValueError as well.
try: empty_list = [] empty_list.remove(5) except ValueError as e: print(e) # list.remove(x): x not in list
That’s all!