I want to create an empty array and add items to it one at a time, similar to Python lists:
xs = []
for item in data:
xs.append(item)
Can I use this approach with NumPy arrays, or is there a better way to create empty NumPy array and append elements efficiently?
Hey! I’ve tried this exact pattern before
. You can start with an empty NumPy array and append items like this:
import numpy as np
arr = np.array([]) # empty array
for item in data:
arr = np.append(arr, item)
It works fine for small datasets.
Caveat: np.append
creates a new array each time, so it’s not very efficient for large loops.
If you know the number of items in advance, I usually pre-allocate the array:
import numpy as np
arr = np.empty(len(data)) # creates an empty array of the desired size
for i, item in enumerate(data):
arr[i] = item
This avoids repeated copying and is much faster on large datasets.
I always use this method when performance matters.
A pattern I often use is combining Python lists with NumPy at the end:
import numpy as np
xs = []
for item in data:
xs.append(item)
arr = np.array(xs)
Works well for unknown sizes.
Keeps the code simple and readable.
I usually use this for quick scripts or when performance is not critical.