0

I want to delete all the elements from a Numpy array except the last element and return the Numpy array. For eg: arr = np.array([4, 5, 6, 7, 8, 9, 10, 11]) Output should be:: arr = [11]

Please let me know how can I achieve this.

1
  • Maybe you can try arr[-1:] Commented Apr 19, 2022 at 8:33

2 Answers 2

1

We can slice using -1 to start from the last item.

import numpy as np

arr = np.array([4, 5, 6, 7, 8, 9, 10, 11]) 
last_arr = arr[-1:]
print (last_arr)

gives

[11]

We can use arr[-1] to get the value of the last element, but it gives us the value 11 and not as an array [11] as you want. We can then create a new array, but this is a longer way to do it.

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

1 Comment

For sure getting the last part of the array is a better idea than creating a new one, so you deserve my upvote. +1
0

You can simply write:

arr[-1] # This is the last element

so you can assign something this way:

arr = np.array([arr[-1]]) # A numpy.array containing only the last element of the other one

Otherwise, if you only want a list containing the last element:

new = [arr[-1]]

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.