In this tutorial, we will look at how to remove the last element from a Numpy array with the help of some examples.

## How do I remove the last element of a Numpy Array?

You can use the numpy `delete()`

function to remove the last element of a numpy array. The following is the syntax –

# remove last element from numpy array ar, assuming numpy imported as np np.delete(ar, len(ar)-1)

The `np.delete()`

function is used to remove an element using its index. Since we want to remove the last element, we pass its index which is one less than the length of the array. It returns a copy of the original array with the specific element deleted.

Alternatively, you can also slice the original array from its start to the second last element to get a new numpy array with the last element removed from the original array.

Note that numpy arrays are immutable. That is, they cannot be modified after creation.

## Steps to remove the last element in Numpy

Let’s now look at a step-by-step example of using the methods mentioned above –

### Step 1 – Create the numpy array

First, we will create a numpy array that we will be using throughout this tutorial.

import numpy as np # create numpy array ar = np.array([10, 20, 30, 40, 50]) # print the array print(ar)

Output:

[10 20 30 40 50]

Here we use the `np.array()`

function to create a numpy array from a list of numbers. We now have a numpy array containing the numbers 10, 20, 30, 40, and 50.

### Step 2 – Remove the last element from the array

First, let’s use the `np.delete()`

function to remove the last element of the numpy array `ar`

created above.

# remove last element ar_new = np.delete(ar, len(ar)-1) # print the returned array print(ar_new) # print the original array print(ar)

Output:

[10 20 30 40] [10 20 30 40 50]

The resulting array does not have the last element from the original array. You can also see that the original array is not modified.

Let’s now use the slicing method to remove the last element.

# remove last element ar_new = ar[:-1] # print the returned array print(ar_new) # print the original array print(ar)

Output:

[10 20 30 40] [10 20 30 40 50]

Here, we slice the original array from its start to the last element (but not including the last element). We use a negative index here for simplicity. We get the same result as above. A copy of the original array with the last element removed.

For more on slicing numpy arrays, refer to numpy’s guide on indexing and slicing.

You might also be interested in –

- How to remove elements from a numpy array?
- Remove First Element From Numpy Array
- Trim zeros from a numpy array in Python

**Subscribe to our newsletter for more informative guides and tutorials. ****We do not spam and you can opt out any time.**