Adding values to array

I tried to add np array to an np empty array and yet failed. Like this:

length = 10
arr = np.empty(length)
for i in range(length):
    sub_arr # an np array, generated by some code, length of sub_arr of each loop is different
    arr[i] = sub_arr

The above code works only when I add a single value, say a float, instead of the sub_arr
Is the only way to achieve this is by list append and convert the list to np array? Like this:

length = 10
list_empty = []
for i in range(length):
    sub_arr # generated by some code, length  of sub_arr of each loop is different
    list_empty.append(sub_arr)
final_arr = np.array(list_empty)

Many thanks.

Setting an element with an array also doesn’t work with recent versions of Numpy (without Numba). It’s also not a good idea to begin with.

For some cases it might be possible to use a 2D array for this, if the maximum length of sub_arr is known upfront (and reasonable).

Perhaps this project is of interest:
https://awkward-array.org/doc/main/index.html

1 Like

OK. I got it. Many thanks for your reply.