# Duplicate mapped elements in Riffle

What is the best way to do this?

in:

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


out:

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


If[Length[#[[2]]] > 0, Transpose[{Table[#[[1]], {x, Length[#[[2]]]}], #[[2]]}], #]
& /@ Partition[Riffle[{a, b, c}, {d, {e, f}, g}], 2]


seems a bit longwinded.

• Just for fun, not good for numbers :) : Flatten[MapThread[ArcTan, {{a, b, c}, {d, {e, f}, g}}]] /. ArcTan -> List.
– Kuba
Feb 20, 2015 at 19:27
• @Kuba You jogged a memory. I think this question is a duplicate. I remember writing this before: Quiet@Re[{a, b, c}, {d, {e, f}, g}] /. Re -> List. Let me see if I can find it. Feb 20, 2015 at 19:32
• Related: (17400), and my answer with Re: (28693). Sadly no votes. :'-( Feb 20, 2015 at 19:34
• This question is almost a duplicate of 17400 linked above, but flat output is desired. I don't know if that is enough to keep this open or not. I'll let the community votes decide. Feb 20, 2015 at 19:35

l1 = {a, b, c};
l2 = {d, {e, f}, g};



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

or

(## & @@ Thread @ #) & /@ Thread[{l1, l2}]


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

• very nice .....:) Feb 20, 2015 at 19:02

Using undocumented Function syntax, Listable, and v10 Composition syntax:

fn1 = #[[2, 1]] & @* Reap @* Function[, Sow[{##}], Listable];

fn1[{a, b, c}, {d, {e, f}, g}]

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


This works at deeper levels as well:

fn1[{a, b, c}, {d, {{e1, e2}, f}, g}]

{{a, d}, {b, e1}, {b, e2}, {b, f}, {c, g}}


Another method without the undocumented functionality:

With[{h = Unique["h", Listable]},
fn2 = Cases[h[##], h[e__] :> {e}, -1] &
]


Test:

fn2[{a, b, c}, {d, {{e1, e2}, f}, g}]

{{a, d}, {b, e1}, {b, e2}, {b, f}, {c, g}}

• great :) Its a bit strange though because the double slot is pink in my Mathematica ... it works though! Feb 20, 2015 at 19:24
• @martin Please see the alternative I added. Feb 20, 2015 at 19:29
• Nice alternative to using SetAttributes there, I'll have to remember that! Feb 20, 2015 at 20:58
• @Simon Thank Oleksandr: (15032) Feb 21, 2015 at 1:23

One way:

ff = Flatten[#, 1] &;
ff@MapThread[Function[{u, v}, {u, #} & /@ ff[{v}]], {{a, b, c}, {x, {y, u}, z}}]

(* {{a, x}, {b, y}, {b, u}, {c, z}}*)

• that's a bit more elegant :) Feb 20, 2015 at 18:40
l1 = {a, b, c};
l2 = {d, {e, f}, g};
Level[Thread[{#, #2}] & @@@ Transpose[{l1, l2}], {-2}]
(*{{a, d}, {b, e}, {b, f}, {c, g}}*)

• This does assume that list elements are atomic, but +1. Feb 21, 2015 at 7:07

Using ReplaceAll with Splice (since V. 13.1)

l1 = {a, b, c};
l2 = {d, {e, f}, g};

Transpose[{l1, l2}] /. {a_, {b_, c_}} :> Splice[{{a, b}, {a, c}}]


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

Update

MapThread[Thread@*List,{l1,l2}]//FlattenAt[2]

(* {{a,d},{b,e},{b,f},{c,g}} *)


Or

Level[MapThread[Thread@*List,{l1,l2}],{-2}]

(* {{a,d},{b,e},{b,f},{c,g}} *)


MapThread[Thread[Distribute[{##}]]&,{l1,l2}]//FlattenAt[2]

Level[MapThread[Thread[Distribute[{##}]]&,{l1,l2}],{-2}]