# How to insert elements at different locations of a given list

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?

• Dirty trick: Block[{k = 0}, Insert[{a, b, c, d, r, m, n}, Unevaluated[{2, 3}[[++k]]], {{3}, {7}}]] – J. M. will be back soon Sep 27 '18 at 13:02
• @J.M. Wow, that one is really dirty. I had to read it several times to understand it half way at least... – Henrik Schumacher Sep 27 '18 at 14:48
• @Henrik, I didn't want to post it as an answer lest it be thought of as an endorsement. ;D – J. M. will be back soon Sep 27 '18 at 14:52
• – user1066 Sep 28 '18 at 0:07

Look what I found after spelunking:

GroupTheoryPermutationGroupsPrivateFoldInsert[
{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... =/

• Wow! $\phantom{}$ – J. M. will be back soon Sep 27 '18 at 14:53
• I wonder if this package has similar functions. – Αλέξανδρος Ζεγγ Sep 27 '18 at 15:16
• @ΑλέξανδροςΖεγγ That package appears to be very new. Good to know! (... although I won't find it applicable to my own work...) – Henrik Schumacher Sep 27 '18 at 15:26
• @HenrikSchumacher Yes, it is accompanied with a book published just about two months ago. – Αλέξανδρος Ζεγγ Sep 27 '18 at 16:20

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}

insertList[list_, valuePosList_] := ReplacePart[
list,
Apply[
Rule[#2, Sequence[#1, list[[#2]]]] &,
valuePosList
, {1}
]
]
`