Python List remove()

Python list‘s remove method is used to remove first occurrence of any item from the list.If you try to remove element which does not exist in the list, remove method will raise ValueError.


Syntax

Here list1 is object of the list and item is the element which you want to remove.


Return

returns nothing, it just make changes to original list.


Example

Let’s see a very simple example:

list1=[1,2,3,4] #Let's remove 2 from the list list1.remove(2) print("List1:",list1)

Output:

List1: [1, 3, 4]

As you can see, 2 got removed from the list.
Let’s remove element from the list which is repeated in the list.

listOfCountries=['India','China','Bhutan','USA','China','Nepal'] listOfCountries.remove('China') print("list Of Countries:",listOfCountries)

Output:

list Of Countries: [‘India’, ‘Bhutan’, ‘USA’, ‘China’, ‘Nepal’]

As you can see, first occurence of ‘china’ got removed from the list.
Let’s remove the element which does not exists in the list.

listOfCountries=['India','China','Bhutan','USA','China','Nepal'] listOfCountries.remove('South Africa') print("list Of Countries:",listOfCountries)

Output:

ValueError Traceback (most recent call last)
in ()
1 listOfCountries=[‘India’,’China’,’Bhutan’,’USA’,’China’,’Nepal’]
—-> 2 listOfCountries.remove(‘South Africa’)
3 print(“list Of Countries:”,listOfCountries)

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

That’s all about Python List remove() method.

Leave a Reply

Your email address will not be published. Required fields are marked *