Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialise numpy array of unknown length

I want to be able to 'build' a numpy array on the fly, I do not know the size of this array in advance.

For example I want to do something like this:

a= np.array() for x in y:      a.append(x) 

Which would result in a containing all the elements of x, obviously this is a trivial answer. I am just curious whether this is possible?

like image 634
user1220022 Avatar asked Apr 12 '12 10:04

user1220022


People also ask

How do you create an unknown size list in Python?

You can use a list in python, you can use the list. append(item) method in order to insert new elements into it, you don't have to specify the size of the list in order to use it and it will grow as your append more items.


1 Answers

Build a Python list and convert that to a Numpy array. That takes amortized O(1) time per append + O(n) for the conversion to array, for a total of O(n).

    a = []     for x in y:         a.append(x)     a = np.array(a) 
like image 84
Fred Foo Avatar answered Sep 30 '22 12:09

Fred Foo