4

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

1 Answer 1

9

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]
Sign up to request clarification or add additional context in comments.

1 Comment

@Amit Please don't forget to accept the most helpful answer. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.