In this article, we will discuss different ways to add / append single element in a numpy array by using append() or concatenate() or insert() function.

Table of Contents

Add element to Numpy Array using append()

Numpy module in python, provides a function to numpy.append() to add an element in a numpy array. We can pass the numpy array and a single value as arguments to the append() function. It doesn’t modifies the existing array, but returns a copy of the passed array with given value added to it. For example,

import numpy as np

# Create a Numpy Array of integers
arr = np.array([11, 2, 6, 7, 2])

# Add / Append an element at the end of a numpy array
new_arr = np.append(arr, 10)

print('New Array: ', new_arr)
print('Original Array: ', arr)

Output:

New Array:  [11  2  6  7  2 10]
Original Array:  [11  2  6  7  2]

The append() function created a copy of the array, then added the value 10 at the end of it and final returned it.

Add element to Numpy Array using concatenate()

Numpy module in python, provides a function numpy.concatenate() to join two or more arrays. We can use that to add single element in numpy array. But for that we need to encapsulate the single value in a sequence data structure like list and pass a tuple of array & list to the concatenate() function. For example,

import numpy as np

# Create a Numpy Array of integers
arr = np.array([11, 2, 6, 7, 2])

# Add / Append an element at the end of a numpy array
new_arr = np.concatenate( (arr, [10] ) )

print('New Array: ', new_arr)
print('Original Array: ', arr)

Output:

New Array:  [11  2  6  7  2 10]
Original Array:  [11  2  6  7  2]

It returned a new array containing values from both sequences i.e. array and list. It didn’t modified the original array, but returned a new array containing all values from original numpy array and a single value added along with them in the end.

Add element to Numpy Array using insert()

Using numpy.insert() function in the NumPy module, we can also insert an element at the end of a numpy array. For example,
C
Output:
O

We passed three arguments to the insert() function i.e. a numpy array, index position and value to be added. It returned a copy of array arr with value added at the given index position. As in this case we wanted to add the element at the end of array, so as the index position, we passed the size of array. Therefore it added the value at the end of array.

Important point is that it did not modifies the original array, it returned a copy of the original array arr with given value added at the specified index i.e. as the end of array.

Summary:

We learned about three different ways to append single element at the end of a numpy array in python.