How to Delete a List Element by Value in Python

Created
Modified

Using list.remove Function

The list.remove(x) function removes the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.

See the following example:

#!/usr/bin/python3

l = ["a", "c", "b", "c"]

if 'c' in l:
  l.remove("c")
print(l)

# try:
#   l.remove('c')
# except ValueError:
#   pass
['a', 'b', 'c']

Using List Comprehension

To remove all occurrences of an element, use a list comprehension:

#!/usr/bin/python3

l = ["a", "c", "b", "c"]
l = [x for x in l if x != 'c']
print(l)
['a', 'b']

Using filter Function

To take out all occurrences, you could use the filter function in python. For example, it would look like:

#!/usr/bin/python3

l = ["a", "c", "b", "c"]

l = list(filter(lambda x: x != 'c', l))
print(l)
['a', 'b']

Python Errors

ValueError:

# ...
l.remove("e")
  l.remove("e")
ValueError: list.remove(x): x not in list

Related Tags