Python - Delete item from array by its value

By: Varghese Chacko 1 year, 2 months ago

Python logoOften we encounter the situation where we need to remove item from array by value. For example, if we have an array [23, 1, 54, 32, 34, 8, 23]. We don't know or we are not sure about the index of the value 32, but we need to delete it. Python array has the built in function remove. For example

>>> x = [23, 1, 54, 32, 34, 8, 23]
>>> x
[23, 1, 54, 32, 34, 8, 23]
>>> x.remove(54)
>>> x
[23, 1, 32, 34, 8, 23]
>>>

As you can see, the remove function deletes the value from the array, but does not return anything. If the value trying to remove isnot in the list, it will raise ValueError exception.

>>> x = [23, 1, 54, 32, 34, 8, 23]
>>> x.remve(100)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'remve'
>>> 

If there exists more than one occurances of the value, it removes the first occurance.

>>> x = [23, 1, 54, 32, 34, 8, 23, 54]
>>> x.remove(54)
>>> x
[23, 1, 32, 34, 8, 23, 54]
>>> 

Comments