Table of Contents
In this tutorial, we will see about Python List‘s remove method.Python List remove method is used to remove passed element from the list.It will remove first matching element from the list.
Python List remove syntax
1 2 3 |
list1.remove(element) |
here list1 is object of list.
Python List remove example
You can simply call remove method to delete an element from the list.
Let’s understand this with the help of simple example.
1 2 3 4 5 |
listOfCars=['Honda','Hyundai','Maruti','Suzuki'] listOfCars.remove('Maruti') print("listOfCar:",listOfCars) |
Output:
As you can see here, ‘Maruti’ got removed from the list.
What if passed element is not in the list?
If element is not in the list, then remove method will raise ValueError.
1 2 3 4 5 |
listOfCars=['Honda','Hyundai','Maruti','Suzuki'] listOfCars.remove('Punto') print("listOfCar:",listOfCars) |
Output:
ValueError Traceback (most recent call last)
1 listOfCars=[‘Honda’,’Hyundai’,’Maruti’,’Suzuki’] —-> 2 listOfCars.remove(‘Punto’)
3 print(“listOfCar:”,listOfCars)
ValueError: list.remove(x): x not in list
That’s all about Python List remove method. Also, check how to remove last element from list in python.