How to join several list putting some fixed list between?

Like this



{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}] &
| improve this answer | |
  • 2
    $\begingroup$ 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}] &. $\endgroup$ – WReach Jan 4 '15 at 22:22
  • $\begingroup$ @WReach Oh, good catch, thanks a lot! $\endgroup$ – Martin Ender Jan 4 '15 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.

| improve this answer | |
  • $\begingroup$ What is "@*"? Can't find it $\endgroup$ – Suzan Cioc Jan 4 '15 at 17:52
  • $\begingroup$ @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). $\endgroup$ – Martin Ender Jan 4 '15 at 17:52
  • $\begingroup$ @MartinBüttner: It's actually new in Mathematica 2 :) $\endgroup$ – DumpsterDoofus Jan 4 '15 at 17:53
  • $\begingroup$ @DumpsterDoofus Oh... then I only discovered it recently. (Ah, RightComposition aka /* is what's new in 10.) $\endgroup$ – Martin Ender Jan 4 '15 at 17:53
  • $\begingroup$ Apparently it existing but not shortened to "@*" in my Mathematica. $\endgroup$ – Suzan Cioc Jan 4 '15 at 18:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.