# Insert at specific resulting positions in multidimensional list?

I have an initial "multidimensional" list (that is, a list that is not a vector):

list0 = {{1},{2,3,4},{3,4},{5}};


and I want to insert elements x,y,z at specific positions {1,1}, {2,3}, {4,2}, to obtain the resulting list:

{{x,1},{2,3,y,4},{3,4},{5,z}}


That is, the list of positions {1,1}, {2,3}, {4,2} gives the positions in the resulting list.

What's a clean way to do this?

This is a generalization of Insert at specific resulting positions?, which is a one-dimensional version of this question.

• @Kuba Typo. Fixed. Dec 4, 2014 at 18:19
• What when positions are {2,2} and {2,3} for example, should it behave like Insert so: ... {2, x, 3, y, 4}... or rather {2, x, y, 3, 4}? Where the latter is maybe intuitive but not consistent with Insert.
– Kuba
Dec 4, 2014 at 18:30

The function insertF in the answer to your linked question also works for the multidimensional case:

insertF = Fold[Insert[#, #2[[1]], #2[[2]]] &, #,  SortBy[Transpose[{#2, #3}], Last]] &;

list0 = {{1},{2,3,4},{3,4},{5}};
parts = {{1, 1}, {2, 3}, {4, 2}};
insertF[list0, {x, y, z}, parts]
(* {{x, 1}, {2, 3, y, 4}, {3, 4}, {5, z}} *)

list0 = {{1},{2,3,4},{3,4},{5}};
parts2 = {{1, 1}, {2, 3}, {4, 2}};
insertF[list0, {x, y,  z}, parts2]
(* {{1}, {2,x,y,3,4}, {3,4}, {5,z}} *)

inserttt[where_, what_, whereExactly_] := (
# = 0;
Insert[where, Unevaluated[what[[++#]]], whereExactly]
) & @ Unique["whatever"]

inserttt[{{1}, {2, 3, 4}, {3, 4}, {5}},
{x, y, z},
{{2, 2}, {2, 3}, {4, 2}}]

 {{1}, {2, x, 3, y, 4}, {3, 4}, {5, z}}


### old, incorrect, failing with {{2,2}, {2,3}.. cases:

I find your description not consistent with code samples, but here is what I've understood:

inserttt[where_, what_, whereExactly_] := ReplacePart[
Insert[where, "", whereExactly],

{{x, 1}, {2, 3, y, 4}, {3, 4}, {5, z}}

• That doesn't work as I want. The position of y in {{1}, {2, x, 3, y, 4}, {3, 4}, {5, z}} is {2,4}, but I want it to be {2,3}. The output I expect from inserttt[{{1}, {2, 3, 4}, {3, 4}, {5}}, {x, y, z}, {{2, 2}, {2, 3}, {4, 2}}] is {{1},{2,x,y,3,4},{3,4},{5,z}} Dec 4, 2014 at 18:48