Python List remove()

Python List remove() is a built-in function that removes the first occurrence element from the list.

In this tutorial, we will learn about the Python list remove() method with the help of examples.

Syntax of List remove() 

The syntax of the remove() method is:

list.remove(element)

remove() Parameters

The remove() method takes a single parameter.

  • element – The element or value that needs to be removed from the list.

If the element doesn’t exist, it will throw ValueError: list.remove(x): x not in list exception.

Return Value from List remove()

The remove() method does not return any value.

Note: The list remove() will remove the first occurrence of the element from the list.

Example 1: Remove element from the list

# list of cars
cars = ['Benz','BMW','Ford','Ferrari','volkswagen']

# remove Ferrari car from the list
cars.remove('Ferrari')

# Updated car list
print("Updated Car list = ",cars)

Output

Updated Car list =  ['Benz', 'BMW', 'Ford', 'volkswagen']

Example 2: remove() method when list has duplicate items

If the list has duplicate element, the remove() method will only remove the first occurence of the matching element.

The ‘BMW’ is found at index 2 and as well as at index 5. But only the first occurrence at index 2 is removed in this case.

# list of cars
cars = ['Benz','BMW','Ford','Ferrari','volkswagen','BMW']

# remove BMW car from the list
cars.remove('BMW')

# Updated car list
print("Updated Car list = ",cars)

Output

Updated Car list =  ['Benz', 'Ford', 'Ferrari', 'volkswagen', 'BMW']

Example 3: Deleting element that doesn’t exist in the List

If you pass an invalid element that does not exist in the list Python will raise ValueError: list.remove(x): x not in list.

# list of cars
cars = ['Benz','BMW','Ford','Ferrari','volkswagen','BMW']

# remove Skoda car from the list
cars.remove('Skoda')

# Updated car list
print("Updated Car list = ",cars)

Output

Traceback (most recent call last):
  File "c:\Personal\IJS\Code\main.py", line 5, in <module>
    cars.remove('Skoda')
ValueError: list.remove(x): x not in list
Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
Python String To Datetime Conversion

Python string to datetime Conversion

Table of Contents Hide Convert Python String to datetime using datetime ModulePython String to datetimePython String to datePython String to timeConvert Python String to datetime using dateutil There are several…
View Post