[Numpy-discussion] initializing an array of lists

Pauli Virtanen pav+sp@iki...
Mon Nov 9 12:09:43 CST 2009


Sat, 07 Nov 2009 21:56:29 -0600, alan wrote:
> I want to build a 2D array of lists, and so I need to initialize the
> array with empty lists :
> 
> myarray = array([[[],[],[]] ,[[],[],[]]])
> 
> Is there a clever way to do this? I could define the array
> 
> myarray = zeros( (xdim,ydim), dtype=object) and then iterate through the
> elements initializing then to empty lists, but surely there is a better
> way.

This question seems to come up from time to time (= maybe should be a 
FAQ?). You can for example vectorize the list constructor:

>>> filler = np.frompyfunc(lambda x: list(), 1, 1)
>>> a = np.empty((3, 4), dtype=np.object)
>>> filler(a, a);
array([[[], [], [], []],
       [[], [], [], []],
       [[], [], [], []]], dtype=object)
>>> a[0,3].append(9)
>>> a
array([[[], [], [], [9]],
       [[], [], [], []],
       [[], [], [], []]], dtype=object)

-- 
Pauli Virtanen



More information about the NumPy-Discussion mailing list