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

np.insert() -1 as the position of an element

I am playing with the NumPy library and there is a behaviour that I do not understand:

I defined a simple vector Y:

Y = np.array([6,7,8],dtype = np.int16)

Then, I tried to add an additional element at the end of the array using the np.insert() method. I specified the position to be at -1:

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

Z = np.insert(Y,(-1),(19))

My element was inserted not on the last, but on the penultimate position:

Output

Could somebody explain my why this element was not inserted at the end of my array?

>Solution :

Negative indexes are calculated using len(l) + i (with l being the object and i being the negative index).

For example, with a list x = [1, 2, 3, 4] the index -2 is calculated as 4-2 = 2, so x[-2] returns 3

In this example, the index -1 is calculated as index 2

Therefore, 19 is inserted at index 2, the penultimate position. To fix this, use Z = np.insert(Y, len(Y), 19).

PS – this is the same with list.insert, not just with numpy arrays

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