0

If I want to select all elements of a NumPy array, up to index N, I can write:

x = my_array[:N]

For example, if I want to select all elements, up to index 5, I can write:

N = 5
x = my_array[:N]

Or, if I want to select all elements, up to and including the penultimate element, I can write:

N = -1
x = my_array[:N]

But what if I want to select all elements up to and including the final element? How can I do this using the above notation?

I tried:

N = -0
x = my_array[:N]

But this returns a blank array.

p.s. Yes, I could just write out x = my_array[:], but I need it to be in the format my_array[:N], where N is defined dynamically.

5
  • Just leave out that value, i.e. array[:] is going to give all. Or do array[:len(array)]. Commented Jan 28, 2019 at 20:08
  • I need to have it in the format my_array[:N], such that N can be dynamically defined Commented Jan 28, 2019 at 20:09
  • 2
    Then use N = len(array). Actually you can use any N >= len(array) for that purpose. Also N = None will do. Commented Jan 28, 2019 at 20:10
  • np.s_[::] produces: slice(None, None, None). Commented Jan 28, 2019 at 21:52
  • either N == len(array) or N == None should work, I'm pretty sure Commented Jan 28, 2019 at 22:21

1 Answer 1

2

Using your method:

N = len(my_array)
x = my_array[:N]

You could then specify any arbitrary value of N if you only wish to slice up to that index. You could also specify the length of your array directly, if known.

To illustrate this...

my_array = [1, 2, 3, 4, 5]
N = len(my_array)
x = my_array[:N]
my_array == x

...returns True.

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

Comments

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.