w3resource

Python List: remove() Method

remove() Method

The  remove() method is used to remove the first occurrence of a given element from a list.

Visual Explanation:

Python List: remove() method

Syntax:

list.remove(x)

Parameter: Required. The element we want to remove. Type -> Any type (string, number, list etc.)

Return Value:

  • Remove the first item from the list whose value is equal to x.
  • It raises a Value Error if there is no such item.

Example 1: Remove an element from a list


colors = ['Red', 'Green', 'Orange', 'Pink']
print("Original List:")
print(colors)
print("Remove 'Green' color from the said list:")
colors.remove('Green')
print('Updated List:', colors)

Output:

Original List:
['Red', 'Green', 'Orange', 'Pink']
Remove 'Green' color from the said list:
Updated List: ['Red', 'Orange', 'Pink']

Example 2: Remove an element that is not present in a list


colors = ['Red', 'Green', 'Orange', 'Pink']
print("Original List:")
print(colors)
print("Remove 'White' color from the said list:")
colors.remove('White')
print('Updated List:', colors)

Output:

Original List:
['Red', 'Green', 'Orange', 'Pink']
Remove 'White' color from the said list:
Traceback (most recent call last):

  File ~\untitled10.py:5 in 
    colors.remove('White')

ValueError: list.remove(x): x not in list

Python Code Editor:

Previous: Python List pop() Method.
Next: Python List reverse() Method.

Test your Python skills with w3resource's quiz



Follow us on Facebook and Twitter for latest update.