How to add zeros before and after each element in a list?

Upsample[{0.2, 0.5, 0.7}, 3, 2]

{0., 0.2, 0., 0., 0.5, 0., 0., 0.7, 0.}

(Thanks: corey979)


This should be fast:

addZeros[arr_] :=
 Module[{res = ConstantArray[0, 3 Length[arr]]},
  res[[2 ;; -2 ;; 3]] = arr;
  res
 ]

If you use floating point numbers instead of integers, use 0. in ConstantArray instead of 0 for improved performance.


Here's a performance-focused version:

iAddZeros[arr_, z_] := 
 Module[{res = ConstantArray[z, 3 Length[arr]]}, 
  res[[2 ;; -2 ;; 3]] = arr;
  res
 ]

addZeros[arr_ /; Developer`PackedArrayQ[arr, Real]] := iAddZeros[arr, 0.]

addZeros[arr_ /; Developer`PackedArrayQ[arr, Complex]] := iAddZeros[arr, 0. + 0. I]

addZeros[arr_] := iAddZeros[arr, 0]

Benchmark:

With[{arr = RandomReal[1, 100000]},
 addZeros[arr]; // RepeatedTiming
 ]
(* {0.00024, Null} *)

Another option might be

lst = {0.2,0.5,0.7};
Flatten[{0.,#,0.}&/@lst]

Mathematica graphics