Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from an array in python3

In Python3, how can I remove an array element? I have tried, like this:

In [1]: arr=[13,14,67,23,9]

In [2]: arr.remove(2)

I want to remove the 3rd position element but it's throwing this error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-50-67be49ced0b0> in <module>()
----> 1 arr.remove(2)

ValueError: list.remove(x): x not in list
like image 757
Amit Avatar asked Dec 23 '22 14:12

Amit


1 Answers

You need to use del in case you want to remove an item by index:

>>> arr=[13,14,67,23,9]
>>> del arr[2]
>>> arr
[13, 14, 23, 9]

Because remove just removes the first item with that value, or if it doesn't exist in the list throws the exception you got:

>>> arr=[13,14,67,23,9]
>>> arr.remove(67)
>>> arr
[13, 14, 23, 9]
like image 135
MSeifert Avatar answered Jan 12 '23 04:01

MSeifert