Python List remove()

Previous
Next

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

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.

listOfCars=['Honda','Hyundai','Maruti','Suzuki'] listOfCars.remove('Maruti') print("listOfCar:",listOfCars)

Output:

listOfCar: [‘Honda’, ‘Hyundai’, ‘Suzuki’]

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.

listOfCars=['Honda','Hyundai','Maruti','Suzuki'] listOfCars.remove('Punto') print("listOfCar:",listOfCars)

Output:

—————————————————————————
ValueError Traceback (most recent call last)
in ()
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.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog