# Insert at specific resulting positions? (Another option) [duplicate]

I found the answer in this post very interesting to do what I need, but I would like something where I could provide a list to be modified, a list with values that will be added and a list with the positions of the values to be added.

Something to get this result:

listaInicial = {0, 1, 2, 3, 4, 5, 6, 7};
listaModificadora = {a, b, c, d, e};
listaPosições = {2, 6, 7, 8, 13};
Fold[Insert[#, #2[[1]], #2[[2]]] &, listaInicial, {{a, 2}, {b, 6}, {c,
7}, {d, 8}, {e, 13}}]


{0,a,1,2,3,b,c,d,4,5,6,7,e}

P.S:I think it should be very obvious, but I am still suffering with Slot function. One day I will be able to understand this function with a lot of training.

## marked as duplicate by corey979, m_goldberg, Yves Klett, Feyre, MarcoBOct 22 '16 at 16:44

• I studied how it behaves the Riffle function, but it does not help much. This function follows a fixed sequence: Riffle[{1, 2, 3, 4, 5, 6, 7, 8, 9}, {x, y}, {5, -1, 2}]. >{1,2,3,4,x,5,y,6,x,7,y,8,x,9,y} – JPeter Oct 21 '16 at 13:15
• seems a near exact duplicate, though this version got several new perhaps better answers. – george2079 Oct 22 '16 at 12:36
• From the beginning it is presenting that refers to a post. But the solutions in the old post were not according to my needs. – JPeter Oct 22 '16 at 12:54
• I needed three inputs that were not displayed in the old post. – JPeter Oct 22 '16 at 12:56

You can start applying Transpose function:

listaInicial = {0, 1, 2, 3, 4, 5, 6, 7};
listaModificadora = {a, b, c, d, e};
listaPosições = {2, 6, 7, 8, 13};
Fold[Insert[#, #2[[1]], #2[[2]]] &, listaInicial,


{0,a,1,2,3,b,c,d,4,5,6,7,e}

Or

InsertValuePosition[list_, values_, positions_] :=
Fold[Insert[#, #2[[1]], #2[[2]]] &, list,
Transpose[{values, positions}]]



{0,a,1,2,3,b,c,d,4,5,6,7,e}

Here is somewhat obscure one-liner.

data = {0, 1, 2, 3, 4, 5, 6, 7};
new = {a, b, c, d, e};
where = {2, 6, 7, 8, 13};

(RightComposition @@ Thread[Insert[new, where]]) @ data


{0, a, 1, 2, 3, b, c, d, 4, 5, 6, 7, e}

LMC's answer is much in the spirit of Mathematica. Since you don't like slots (while you should - they make lots of things easier) I provide a straightforward Do loop:

lst1 = {0, 1, 2, 3, 4, 5, 6, 7};
lst2 = {a, b, c, d, e};
lst3 = {2, 6, 7, 8, 13};

lst = lst1;
Do[
lst = Insert[lst, lst2[[i]], lst3[[i]]], {i, 1, Length[lst2]}
]
lst


{0, a, 1, 2, 3, b, c, d, 4, 5, 6, 7, e}

listaInicial = {0, 1, 2, 3, 4, 5, 6, 7};
listaModificadora = {a, b, c, d, e};
listaPos = {2, 6, 7, 8, 13};
listIpos =
listaPos]

Normal@SparseArray[listIpos~Join~listaPos ->

out = ConstantArray[0, Length@Join[listaInicial, listaModificadora]];