How do I replace an element with another new element in the same index and move the previous element to the next index

Question:

I have this problem where I want to replace an element with a new element, and instead of removing the element I replaced, I just want it to move to the next index.

import numpy as np

empty_arr = [0] * 5
arr = np.array(empty_arr)


inserted = np.insert(empty_arr, 1, 3)
inserted = np.insert(empty_arr, 1, 4) 

#Output: 
[0 4 0 0 0 0]

I don’t know the right syntax for this but I just want to replace element 3 with 4

#Expected Output:
[0 3 4 0 0 0] #move the element 4 to next index
Asked By: Riri

||

Answers:

You are placing the result of the first insertion in the inserted variable but you are starting over from the original array for the 2nd insertion and overriding the previous result.

You should start the 2nd insertion from the previous result:

inserted = np.insert(empty_arr, 1, 3)
inserted = np.insert(inserted, 1, 4)

BTW, do you have to use numpy arrays for this ? regular Python lists seem better suited:

empty_arr = [0] * 5
empty_arr.insert(1,3)
empty_arr.insert(1,4)

print(empty_arr)

[0, 4, 3, 0, 0, 0, 0] 

Note that if you want 4 to appear after 3 in you result, you either have to insert them in the reverse order at index 1 or insert 4 at index 2 after inserting 3 at index 1.

Answered By: Alain T.
import numpy as np

empty_arr = [0] * 5
arr = np.array(empty_arr)


empty_arr = np.insert(empty_arr, 1, 3)
empty_arr = np.insert(empty_arr, 1, 4) 

#output
array([0, 4, 3, 0, 0, 0, 0])
Answered By: God Is One
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.