# How to insert zeros between elements in a numpy array?

## Issue

I have an nd array, for example this:

``````x = np.array([[1,2,3],[4,5,6]])
``````

I would like to double the size of the last dimension, and insert zeroes between the elements to fill the space. The result should look like this:

``````[[1,0,2,0,3,0],[4,0,5,0,6,0]]
``````

I tried to solve it using `expand_dims` and `pad`. But the `pad` function inserts zeroes not just after each value in the last dimension. The shape of it’s result is `(3, 4, 2)`, but it should be `(2,3,2)`

``````y = np.expand_dims(x,-1)
z = np.pad(y, (0,1), 'constant', constant_values=0)
res = np.reshape(z,[-1,2*3]
``````

Result of my code:

``````array([[1, 0, 2, 0, 3, 0],
[0, 0, 4, 0, 5, 0],
[6, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
``````

How is it possible with `pad` to insert zeroes in the last dimension after each element? Or is there any better way to solve the problem?

## Solution

Simply initialize output array and assign with `slicing`

``````m,n = x.shape
out = np.zeros((m,2*n),dtype=x.dtype)
out[:,::2] = x
``````

Alternatively with stacking –

``````np.dstack((x,np.zeros_like(x))).reshape(x.shape[0],-1)
``````