[Numpy-discussion] non-intuitive behaviour in numpy.array([list], numpy.object_)

Christopher Barker Chris.Barker@noaa....
Thu Jan 3 11:50:05 CST 2008

Garnet Chan wrote:
> When constructing an numpy object array from a list of numpy arrays,
> one observes the following behaviour
>>>> import numpy as N
>>>> a=[N.zeros([2,2], N.object_), N.zeros([2,2], N.object_)]
>>>> b=N.array(a, N.object_)
>>>> print b.shape
> (2, 2, 2)
>>>> a=[N.zeros([2,2], N.object_), N.zeros([2,1], N.object_)]
>>>> b=N.array(a, N.object_)
>>>> print b.shape
> (2,)
> I understand that this is because in the 1st instance, numpy is trying
> to be clever and recognises that the list of arrays "a" can be
> reshaped into a 3-d array. But surely, if we are constructing an array
> with the object_ dtype, the first should also be converted into a
> shape (2,) array?

arrays of the _object dtype are plain weird -- as arbitrary objects can 
be sequences (and mutable ones at that!), it's impossible to 
automatically create the shape of arrays of objects that the user wants. 
Perhaps it could be a bit smarter to be more consistent, but what you 
really need to do is define the shape for numpy, and not expect it to 
figure out what you want -- even if it does the right thing with one 

If you want a (2,) array, then do this:

 >>> b = N.empty(2, dtype=N.object)
 >>> b[:]=a
 >>> b.shape


Christopher Barker, Ph.D.

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception


More information about the Numpy-discussion mailing list