# How can I initialize an empty Numpy array with a given number of dimensions?

## Question:

I basically want to initialize an empty 6-tensor, like this:

``````a = np.array([[[[[[]]]]]])
``````

Is there a better way than writing the brackets explicitly?

You can use empty or zeros.

For example, to create a new array of 2×3, filled with zeros, use: `numpy.zeros(shape=(2,3))`

You could directly use the `ndarray` constructor:

``````numpy.ndarray(shape=(1,) * 6)
``````

Or the `empty` variant, since it seems to be more popular:

``````numpy.empty(shape=(1,) * 6)
``````

Iteratively adding rows of that rank-1 using np.concatenate(a,b,axis=0)

Don’t. Creating an array iteratively is slow, since it has to create a new array at each step. Plus `a` and `b` have to match in all dimensions except the concatenation one.

``````np.concatenate((np.array([[[]]]),np.array([1,2,3])), axis=0)
``````

will give you dimensions error.

The only thing you can concatenate to such an array is an array with size 0 dimenions

``````In [348]: np.concatenate((np.array([[]]),np.array([[]])),axis=0)
Out[348]: array([], shape=(2, 0), dtype=float64)
In [349]: np.concatenate((np.array([[]]),np.array([[1,2]])),axis=0)
------
ValueError: all the input array dimensions except for the concatenation axis must match exactly
In [354]: np.array([[]])
Out[354]: array([], shape=(1, 0), dtype=float64)
In [355]: np.concatenate((np.zeros((1,0)),np.zeros((3,0))),axis=0)
Out[355]: array([], shape=(4, 0), dtype=float64)
``````

To work iteratively, start with a empty list, and `append` to it; then make the array at the end.

`a = np.zeros((1,1,1,1,1,0))` could be concatenated on the last axis with another `np.ones((1,1,1,1,1,n))` array.

``````In [363]: np.concatenate((a,np.array([[[[[[1,2,3]]]]]])),axis=-1)
Out[363]: array([[[[[[ 1.,  2.,  3.]]]]]])
``````

You can do something like `np.empty(shape = [1] * (dimensions - 1) + [0])`.
Example:

``````>>> a = np.array([[[[[[]]]]]])
>>> b = np.empty(shape = [1] * 5 + [0])
>>> a.shape == b.shape
True
``````

This should do it:

``````x = np.array([])
``````
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.