Python List remove() Method

Removes an item from a list


Use remove() method to remove a single item from a list.

The method searches for the first instance of the given item and removes it.

If specified item is not found, it raises ‘ValueError’ exception.



Python list remove() method parameters
itemRequiredAny item you want to remove

Remove Single Item

Example: Remove ‘green’ from the list

L = ['red', 'green', 'blue']
print(L)	# ['red', 'blue']

Example: Remove item from the nested list

L = ['red', 'green', [1, 2, 3]]
L.remove([1, 2, 3])
print(L)	# ['red', 'green']

The remove() method removes item based on specified value and not by index.

If you want to delete list items based on the index, use pop() method or del keyword.

Remove Duplicate Items

remove() method searches for the first instance of the given item and removes it.

Example: Remove only first instance of ‘red’

L = ['red', 'green', 'blue', 'red', 'red']
print(L)	# ['green', 'blue', 'red', 'red']

If you want to remove multiple instances of an item in a list, use list comprehension or lambda expression.

Example: Remove duplicate items from a list

# list comprehension
L = ['red', 'green', 'blue', 'red', 'red']
L = [x for x in L if x is not 'red']
print(L)	# ['green', 'blue']
# lambda expression
L = ['red', 'green', 'blue', 'red', 'red']
L = list(filter(lambda x: x is not 'red', L))
print(L)	# ['green', 'blue']

Removing Item that Doesn’t Exist

remove() method raises an ValueError exception, if specified item doesn’t exist in a list.

Example: remove() raises ValueError if no item found

# ValueError: list.remove(x): x not in list
L = ['red', 'green', 'blue']

To avoid such exception, you can check if item exists in a list, using in operator inside if statement.

Example: Check if item exists before removing an item

L = ['red', 'green', 'blue']
if 'yellow' in L: