Skip to main content
2 of 3
added 18 characters in body
Mr.Wizard
  • 273.1k
  • 34
  • 595
  • 1.4k

Looking for a way to insert multiple elements into multiple positions simultaneously in a list

I would like to take the following data:

insertvalues = {r, x};
insertpositions = {{1}, {5}};
origlist = {a, b, c, d, e, f, g};

and generate output that looks like this:

{r,a,b,c,d,x,e,f,g}

Mathematica's Insert command seems limited in that it does not allow you to insert multiple elements simultaneously into different positions in a list.

I wrote an ugly While loop to accomplish this, and it works, but seems inappropriate for Mathematica's functional approach to coding. Is there a "simpler" way to accomplish this goal with a functional approach? Thank you.

insertvalues = {r, x};
insertpositions = {{1}, {5}};
origlist = {a, b, c, d, e, f, g};

loopcounter = 0; poscounter = 0; final = origlist;
While[loopcounter < Length[insertvalues],
  final = 
   Insert[final, 
    insertvalues[[loopcounter + 
       1]], (insertpositions[[loopcounter + 1]] + poscounter)]; 
  loopcounter++; poscounter++];
Todd Allen
  • 2.1k
  • 5
  • 29
  • 32