Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a number to the end of numpy array with left-shift

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading