This is something I didn't find so easily on the internet. It's easy to create np.arrays, but how do you create an empty one so you can append on the go?
2 Answers
1. A Hack
You can create an empty array using the np.empty() function and specify the dimensions to be (0, 0) and then use np.append() to append items later.
>>> a = np.empty((0, 0))
>>> a
array([], shape=(0, 0), dtype=float64)
>>> b = np.append(a, [1, 2])
>>> b
array([1., 2.])
2. However...
The hack above is not advisable, use it with caution. Appending to lists has O(N) complexity, while appending to arrays has O(N^2) (besides different memory use). The proper way should be, then, to append to lists. Note that using list() on numpy arrays to transform them into lists is not correct, as you will get a list of numpy arrays. Instead, use the .tolist() method.
>>> a = np.array([[1, 2], [3, 4]])
>>>
>>> list(a)
[array([1, 2]), array([3, 4])]
>>>
>>> a.tolist()
[[1, 2], [3, 4]]
    
numpy.ndarrayobjects aren't designed to allow you to do this. Numpy arrays andlistobjects have very different performance trade-offs. If you really want to do this, use a list and convert to an array at the end.np.appendis a linear-time operation. Using it to fill anumpy.arraywill create quadratic-time behavior. In contrast,list.appendis (amoritized) constant time, so overall, it will be linear time to construct the list.numpy.