28

Suppose we have the following array:

import numpy as np
a = np.arange(1, 10)
a = a.reshape(len(a), 1)
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])

Now, i want to access the elements from index 4 to the end:

a[3:-1]
array([[4],
       [5],
       [6],
       [7],
       [8]])
 

When i do this, the resulting vector is missing the last element, now there are five elements instead of six, why does it happen, and how can i get the last element without appending it?

Expected output:

array([[4],
       [5],
       [6],
       [7],
       [8],
       [9]])

1 Answer 1

70

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Understanding slicing

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

Sign up to request clarification or add additional context in comments.

4 Comments

That worked indeed, thanks, i'm trying to convert some matlab code to python/numpy, and that reference guide NumPy fot Matlab users misses some important issues as indexing and slicing.
@Andfoy: I'd recommend reading the NumPy tutorial I linked to. It's not perfect, but should be a good start.
Is there an object or other "index" that can go where the -1 is to make it behave like a[3:]? I often find it would simplify the code I write..
I found the answer--use None--like a[3:None].

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.