1

How would I go about removing an array item from an array in a way that keeps the array index in an incremental list?

Basically I want to do this:

Modify the following array so that it results in the next one

#before
arrayName[0] = "asdf random text"
arrayName[1] = "more randomasdf"
arrayName[2] = "this is the array item i am about to remove"
arrayName[3] = "another asdfds"
arrayName[4] = "and som easdf"

#after
arrayName[0] = "asdf random text"
arrayName[1] = "more randomasdf"
arrayName[2] = "another asdfds"
arrayName[3] = "and som easdf"

Notice how arrayName[2] from the #before array is gone in the #after array and the index has been reordered so that arrayName[3] from the #before array is now arrayName[2].

I want to delete the array item and reorder the array index.

How can I do this efficiently?

1
  • 1
    I'm guessing by "array" you mean a plain Python list, right? (There is no built-in data type called "array" in Python, but there is an array module in the standard library. And some people use "array" in the context of Python to refer to NumPy arrays without explicitly saying so.) Commented Mar 29, 2012 at 0:29

4 Answers 4

5

If by "array" you actually mean "list", you can simply use del:

del arrayName[2]
Sign up to request clarification or add additional context in comments.

Comments

1
>>> a = ["asdf random text", "more randomasdf", "this is the array item i am about to remove", "another asdfds", "and som easdf",]
>>> a
['asdf random text', 'more randomasdf', 'this is the array item i am about to remove', 'another asdfds', 'and som easdf']
>>> a.pop(2)
'this is the array item i am about to remove'
>>> a
['asdf random text', 'more randomasdf', 'another asdfds', 'and som easdf']

Comments

0

just use the del command

del(arrayName[2])

python will automatically re-order it for you

Comments

0

Assuming the array is a python list,you can try del arrayName[2] or arrayName.pop(2). The complexity of each deletion is O(N), N is the length of the list.

If the arrayName's length or the number of the indexes you want to delete is really large,you may try this.

indexestodelete = set(2,.....)
arrayName[:] = [arrayName[index] for index not in indexestodelete ]

Comments

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.