Python List remove() Method
Removes the first item with the specified value.
Syntax
Python
Copy Code
list.remove(value)
Parameters
Parameter | Description |
---|---|
value |
Required. The value of the item to be removed. The value can be of any type. |
Example
Python
Copy Code
groceries = ['apples', 'oranges', 'paper towels', 'apples'] groceries.remove('apples') print(groceries)
Output
['oranges', 'paper towels', 'apples']
Be aware that
remove
will only
remove the first occurrence of an item, and not all occurrences. To remove all occurances
you could do something like
Python
Copy Code
groceries = ['apples', 'oranges', 'paper towels', 'apples'] while groceries.count('apples') > 0: groceries.remove('apples')
Notes
If the value does not exist in the list, Python will throw a ValueError exception.
Example
Python
Copy Code
groceries = ['apples', 'oranges', 'paper towels'] groceries.remove('bananas')
Output
Traceback (most recent call last): File "Lists.py", line 2, in <module> groceries.remove('bananas') ValueError: list.remove(x): x not in list