Python List remove() method
The list.remove () method in Python removes the item at the specified position in the given list.
Syntax
1 2 3 |
list.remove(x) |
Parameter
x: This parameter represents the element you want to remove and accepts any type (string, number, list etc.)
Example 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Python program explaining # the list.remove () method fruitVal = ['apple', 'banana', 'cherry'] print("Fruit list: \n",fruitVal) # inserting more fruits in the list print("After inserting more fruits in the list: ") fruitVal.insert(4, "Kiwi") fruitVal.insert(5, "orange") fruitVal.insert(6, "Fig") print(fruitVal) # removing fig from the list fruitVal.remove("Fig") fruitVal.remove("orange") print("After removing few fruits from the list:") print(fruitVal) |
Output
1 2 3 4 5 6 7 8 |
Fruit list: ['apple', 'banana', 'cherry'] After inserting more fruits in the list: ['apple', 'banana', 'cherry', 'Kiwi', 'orange', 'Fig'] After removing few fruits from the list: ['apple', 'banana', 'cherry', 'Kiwi'] |
Example 2
1 2 3 4 5 6 7 8 9 10 |
# Python program explaining # the list.remove() method # animal list animal = ['cat', 'dog', 'rabbit', 'pig'] # removing an element which is not present in the list animal.remove('elephant') #an error will be raised print('Updated animal list: ', animal) |
Output
1 2 3 4 5 6 |
Traceback (most recent call last): File "main.py", line 7, in <module> animal.remove('elephant') ValueError: list.remove(x): x not in list |