How to Add and Remove Elements from NumPy Arrays

Giulio Laurenti, PhD
9 min readOct 18, 2024
Photo by Sanni Sahil on Unsplash

In a previous article, we learned different ways to create NumPy arrays.

Here, we will learn how to add and remove elements from an array.

Before we start, let’s import Numpy as np.

import numpy as np

Adding elements to an array
Numpy has two functions that allow us to add elements to an array:

  • append(): adds elements at the end of the array
  • insert(): adds elements in a specific position of the array

append()
NumPy append() takes three parameters: array, values and axis.

The axis parameter is only relevant for arrays with two or more dimensions.

Let’s start with appending elements to 1D arrays.

# Create a 1D array containing 4 random integers between 20 and 80.

arr = np.random.randint(20, 80, size = 4)
arr

array([51, 28, 21, 27])

# Now let's append the number 62 at the end of the array

np.append(arr, 62)
array([51, 28, 21, 27, 62])

append() creates a copy of the array. To modify the original array, we need to assign the result of append() to it.

# append() did not modify the original array

arr

array([51, 28, 21, 27])

# If we…

--

--

Giulio Laurenti, PhD
Giulio Laurenti, PhD

Written by Giulio Laurenti, PhD

A Molecular Biologist who enjoys writing about programming, science, and the wonderful world around us.

No responses yet