Skip to content

NumPy array append

  • by

In NumPy, the append function is not recommended for appending elements to an existing array, as it creates a new array every time it is called, resulting in inefficient memory usage. It is more efficient to preallocate the array with the desired size and then fill it with the desired values.

However, if you still want to use the append function, you can do so by following these steps:

import numpy as np

# Create an initial array
arr = np.array([1, 2, 3])

# Append a single element
new_element = 4
arr = np.append(arr, new_element)

print(arr)  # Output: [1 2 3 4]

# Append multiple elements
new_elements = [5, 6, 7]
arr = np.append(arr, new_elements)

print(arr)  # Output: [1 2 3 4 5 6 7]

Output:

NumPy array append

Do comment if you have any doubts or suggestions on this NumPy Array topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *