I want to create a very large vector of numbers, but the length of that vector is not known. However, I could give a maximum length (which would be around 100k), although most likely the list will actually be around 10k. Essentially, I have a for loop, within which I keep adding numbers to the vector, until a certain criterion is met.
My first attempt at doing this was with Python lists, where I used the following:
x = []
for i in range(K):
y = get_list_of_numbers()
x += y
However, ultimately I want to convert this list to a NumPy array, for further processing. If I do this using a = np.array(x), it takes a very long time to create that array.
So, my second solution was to create an empty NumPy array from the beginning, and add elements to it as I go along:
x = np.empty([])
for i in range(K):
y = get_list_of_numbers()
np.append(x, y)
However, here the np.append(x, y) takes a very long time to process.
So, both my solutions are very slow. Is there a quicker solution out there?
The only remaining solution I can think of is to create a huge NumPy array at the maximum length, and then insert each element into the appropriate slot in that array. However, this would be very memory inefficient, as I do not really have a good estimate of the maximum vector length...
Thanks!
np.zeros/emptyand finally slice. - Divakarnp.appendis wrong - stay away from that function. The list append approach is usually fastest - even if the finalnp.arraycall takes time. stackoverflow.com/questions/43237035/… - hpaulj