# How to join several list interleaving with some fixed list between?

How to join several list putting some fixed list between?

Like this

MyJoin[{{a,b},{c,d},{e,f}},{x}]


giving

{a, b, x, c, d, x, e, f}


This is like join with connector.

You can use Riffle and Join:

MyJoin[list_,glue_] := Join @@ Riffle[list, {glue}]


or as a pure function

MyJoin = Join @@ Riffle[#, {#2}] &

• The exhibited function does not work for the example shown in the question. This is because Riffle interprets a list in the second argument as a cyclic replacement specification. The second argument must be wrapped in a list to work around this interpretation: MyJoin[list_,glue_] := Join @@ Riffle[list, {glue}] or MyJoin = Join @@ Riffle[#, {#2}] &. Jan 4, 2015 at 22:22
• @WReach Oh, good catch, thanks a lot! Jan 4, 2015 at 22:26

You can also use this:

MyJoin = Flatten@*Riffle;

MyJoin[{{a, b}, {c, d}, {e, f}}, {x}]
(*{a, b, x, c, d, x, e, f}*)


As Martin Büttner pointed out, this will flatten internal structures in nested lists, which may or may not be what you are looking for.

• What is "@*"? Can't find it Jan 4, 2015 at 17:52
• @SuzanCioc It's function composition. Note that using Flatten will not preserve any structure within your initial list (i.e. if either argument contains nested lists, those will be flattened as well). Jan 4, 2015 at 17:52
• @MartinBüttner: It's actually new in Mathematica 2 :) Jan 4, 2015 at 17:53
• @DumpsterDoofus Oh... then I only discovered it recently. (Ah, RightComposition aka /* is what's new in 10.) Jan 4, 2015 at 17:53
• Apparently it existing but not shortened to "@*" in my Mathematica. Jan 4, 2015 at 18:11