Insert

Consider the list of ordered pairs (lst) below.

Clear["Global`*"] ; lst = {{x1, y1}, {x2, y2}, {x3, y3}, {x4, y4}, {x5, y5}} ;

Now suppose you want to insert {a1,b1},{a2,b2},{a3,b3}
between the third and fourth ordered pairs. The line below does the trick nicely.

Insert[lst, Unevaluated[Sequence @@ {{a1, b1}, {a2, b2}, {a3, b3}}], 4]

{{x1, y1}, {x2, y2}, {x3, y3}, {a1, b1}, {a2, b2}, {a3, b3}, {x4, y4}, {x5, y5}}

Here Unevaluated is needed since Insert doesn't have a Hold attribute, and we don't want Sequence@@{...} to evaluate until after Insert does it's job.  The use of (Sequence@@) simply strips the head List from the list of ordered pairs.

Notice you can use Insert[expr, elem, {{i1,j1, ...},{i2,j2, ...}, ...}]  to inset an expression at more than one position, but this is very slow if you are inserting at lots (>100) of positions.


Created by Mathematica  (May 16, 2004)

Back to Ted’s Tricks index page