Unlike a Python list's append(), which grows in place, np.append() always creates and returns an entirely new array combining the original data with the appended values, since NumPy arrays have a fixed size and cannot actually be extended in place. Without an axis argument, both arrays are first flattened before being joined into a 1D result; with an axis specified, values must have a compatible shape along the other dimensions, behaving much like np.concatenate() with an extra convenience for appending simple values.
1Understanding np.append()
Unlike a Python list's append(), which grows in place, np.append() always creates and returns an entirely new array combining the original data with the appended values, since NumPy arrays have a fixed size and cannot actually be extended in place. Without an axis argument, both arrays are first flattened before being joined into a 1D result; with an axis specified, values must have a compatible shape along the other dimensions, behaving much like np.concatenate() with an extra convenience for appending simple values.
Calling np.append() repeatedly inside a loop is a common but seriously inefficient anti-pattern — each call copies the entire array so far into a new, larger one, making the total cost quadratic; accumulate values in a plain Python list and convert to an array once at the end instead.
import numpy as np
arr = np.array([1, 2, 3])
result = np.append(arr, [4, 5])
print(result)2Practical Example
Here is a real-world application of np.append() showing how it is used in production NumPy code.
import numpy as np
matrix = np.array([[1, 2], [3, 4]])
result = np.append(matrix, [[5, 6]], axis=0)
print(result)3Best Practices
Follow these guidelines when working with np.append():
1. Never call np.append() repeatedly inside a loop — accumulate values in a Python list first, then convert to an array once with np.array() at the end
2. Use np.concatenate() directly when combining full arrays, reserving np.append() for the specific case of adding a handful of extra values
3. Pre-allocate an array with np.zeros()/np.empty() and fill it by index instead of building it up via repeated append() calls, whenever the final size is known ahead of time
Tip: Calling np.append() repeatedly inside a loop is a common but seriously inefficient anti-pattern — each call copies the entire array so far into a new, larger one, making the total cost quadratic; accumulate values in a plain Python list and convert to an array once at the end instead.
import numpy as np
arr = np.array([1, 2, 3])
result = np.append(arr, [4, 5])
print(result)