I have an numpy array with (1,4) shape of zeros. I want to add numbers in the end of the array and the array element shift to the left.
I expect the below results:
at the beginning:
zeros=[0,0,0]
first iteration (add 1):
[0,0,1]
second iteration (add 2):
[0,1,2]
third iteration (add 3):
[1,2,3]
forth iteration (add 4):
[2,3,4]
>Solution :
First of all, we define a function to shift each element to the left:
def shift_all_to_the_left(array):
for index, element in enumerate(array):
if index == len(array)-1:
continue
array[index] = array[index+1]
return array
After that, we apply the function to our list and we change the last element with the desired one as many times as the number of elements that we want to add:
zeros=[0,0,0]
number_to_add= [1,2,3,4]
for number in number_to_add:
zeros = shift_all_to_the_left(zeros)
zeros[-1] = number
print(zeros)
Output
[0, 0, 1]
[0, 1, 2]
[1, 2, 3]
[2, 3, 4]