8

Say a list is given as

list = {a, b, c, d, r, m, n};

Suppose I want to insert 2 and 3 at position 3 and 7, respectively.

Insert[list, 2, 3] puts 2 at position 3, but Insert[list, {{2, 3}, {3, 7}}] does nothing.

How is it possible?

Soumyajit Roy
  • 684
  • 3
  • 12

3 Answers3

7

How about this

myInsert[list_, valuePosList_] := Fold[Insert[#, Sequence @@ #2] &, 
                                       list, 
                                       SortBy[valuePosList, -Last[#] &]
                                      ]

myInsert[list, {{2, 3}, {3, 7}}]
{a, b, 2, c, d, r, m, 3, n}
6

Look what I found after spelunking:

GroupTheory`PermutationGroups`Private`FoldInsert[
 {a, b, c, d, r, m, n},
 {2, 3}, {3, 7}
 ]

{a, b, 2, c, d, r, 3, m, n}

Well, it is not entirely correct for it does not revert the order of insertion... =/

Henrik Schumacher
  • 106,770
  • 7
  • 179
  • 309
3
insertList[list_, valuePosList_] := ReplacePart[
  list,
  Apply[
   Rule[#2, Sequence[#1, list[[#2]]]] &,
   valuePosList
   , {1}
   ]
  ]

Mathematica graphics

rhermans
  • 36,518
  • 4
  • 57
  • 149