I have an initial list:
list0 = {1,2,3,4,5};
and I want to insert {a,x} at specific positions {1,5}, which means that I want the resulting list to have a at position 1 and x at position 5. This is different from what Mathematica's Insert does, and what has been asked here before (Looking for a way to insert multiple elements into multiple positions simultaneously in a list). In my example, the output I expect is:
In[]: myInsert[list0, {a,x}, {1,5}]
Out[]: {a,1,2,3,x,4,5}
What's a clean way to do this? And what's a good name for this type of insertion?
Multidimensional version: Insert at specific resulting positions in multidimensional list?
Answer
Fold[Insert[#, #2[[1]], #2[[2]]] &, list0, {{a, 1}, {x,5}}]
(* {a, 1, 2, 3, x, 4, 5} *)
Or, define a function:
insertF = Fold[Insert[#, #2[[1]], #2[[2]]] &, #, SortBy[Transpose[{#2, #3}], Last]] &;
(* thanks: @becko *)
insertF[Range@5, {a, x}, {1, 4}]
(* {a, 1, 2, x, 3, 4, 5} *)
insertF[Range@5, {a, w, x}, {1, 5, 4}]
(* {a, 1, 2, x, w, 3, 4, 5} *)
Comments
Post a Comment