Collect elements in a standard Python list first and convert once via np.array(items) (the fastest $O(n)$ approach), or initialize an empty 1D/2D NumPy array with np.empty(0, dtype=...) / np.empty((0, n_cols), dtype=...) and call np.append() / np.vstack() when incremental array concatenation is unavoidable.
Basic Example
import numpy as np
# 1. Recommended (O(n) amortized): Accumulate in a Python list, convert once at the end
rows = []
for i in range(4):
rows.append([i, i * 10])
arr = np.array(rows, dtype=np.int64)
print(arr.shape) # Output: (4, 2)
# 2. Direct 1D empty NumPy array + np.append() (returns a NEW array every call)
arr_1d = np.empty(0, dtype=np.float64)
arr_1d = np.append(arr_1d, [1.5, 2.5])
arr_1d = np.append(arr_1d, 3.5)
print(arr_1d) # Output: [1.5 2.5 3.5]
# 3. Direct 2D empty NumPy array with fixed column count + np.vstack()
arr_2d = np.empty((0, 3), dtype=np.int64)
arr_2d = np.vstack([arr_2d, [10, 20, 30]])
arr_2d = np.vstack([arr_2d, [40, 50, 60]])
print(arr_2d.shape) # Output: (2, 3)
Key Details & Edge Cases
- Why calling
np.append()inside a loop is $O(n^2)$ (and slow):- Unlike
list.append(), NumPy arrays occupy a fixed, contiguous block of C memory and cannot grow in place. Every call tonp.append()allocates a brand-new array and copies all previous elements—turning a 100,000-iteration loop into $\sim 5 \times 10^9$ element copies. - Accumulating in a Python
listand callingnp.array(items)once—or preallocatingnp.empty((n, cols))when the final size is known—is 100× to 1,000× faster on large loops.
- Unlike
np.append()flattens multi-dimensional arrays unlessaxis=is specified:- Calling
np.append(arr_2d, [[7, 8, 9]])withoutaxis=0silently flattens both inputs into a 1D array! - Always pass
axis=0with matching dimensions (np.append(arr_2d, [[7, 8, 9]], axis=0)), or usenp.vstack([arr_2d, [7, 8, 9]])(which automatically promotes a 1D row vector[7, 8, 9]to shape(1, 3)).
- Calling
np.empty(0)vs.np.array([])(dtypetrap):np.array([])defaults todtype=float64. Appending integers (np.append(np.array([]), 5)) silently upcasts your integers to floats (array([5.])).- Always pass an explicit
dtype=(np.empty(0, dtype=np.int64)ornp.empty((0, 3), dtype=np.float32)) so your data type stays deterministic from the first append.
np.emptydoes NOT mean “0 elements” unless shape is0:- Calling
np.empty((3, 2))creates a 6-element array filled with uninitialized garbage RAM values, not an empty 0-row array! Pass0in the growing dimension (np.empty(0)ornp.empty((0, 2))) to create a true zero-element array.
- Calling
Comparison of Array Initialization & Appending Strategies in NumPy
| Strategy | Initialization Syntax | Append / Fill Syntax | Time Complexity ($n$ appends) | Best Used When |
|---|---|---|---|---|
Python list + np.array() (Recommended) |
buf = [] |
buf.append(x) $\rightarrow$ np.array(buf) |
$O(n)$ | Unknown final size in a loop (fastest, cleanest, zero wasted copies). |
| Preallocated Buffer | arr = np.empty((n, cols), dtype=...) |
arr[i] = row |
$O(n)$ (zero reallocation) | Final row/element count n is known upfront (maximum performance). |
np.empty(0) + np.append() |
arr = np.empty(0, dtype=np.int64) |
arr = np.append(arr, val) |
$O(n^2)$ in loops | Occasional one-off 1D additions outside tight loops. |
np.empty((0, k)) + np.vstack() |
arr = np.empty((0, k), dtype=np.int64) |
arr = np.vstack([arr, row]) |
$O(n^2)$ in loops | Incrementally stacking a few 2D rows with a fixed column width k. |
You must log in or register to comment.
