List structure transformation

How to transform a list as

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


into the form of

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


elegantly, without using a loop such as For?

• {p, q} = {{x, y}, {a, b, c, d, e}}; Append[p, #] & /@ q – ubpdqn Nov 13 '16 at 11:06
• Outer[Join, {p}, Partition[q, 1], 1, 1][[1]] – corey979 Nov 13 '16 at 11:11
• First[Outer[Flatten@*List, {#1}, #2, 1, 2] & @@ {{x, y}, {a, b, c, d, e}}] – Marius Ladegård Meyer Nov 13 '16 at 11:11
• Join[p, {#}] & /@ q – Feyre Nov 13 '16 at 11:14
• just because I like Reap/Sow: Last@Reap[Sow @@ {{x, y}, {a, b, c, d, e}}, _, Append[#2[[1]], #1] &] – ubpdqn Nov 13 '16 at 11:17

Flatten /@ Thread[data, List, {2}]


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

Also:

Append @@@ Tuples[{{#}, #2}] & @@ data


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

ClearAll[dat]
dat = {{x, y}, {a, b, c, d, e}}
Append[dat[[1]], #] & /@ dat[[2]]


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

Table[Join[dat[[1]], {dat[[2, i]]}], {i, Length[dat[[2]]]}]


Seems like a good place to use MapThread. Problem is that it wants both lists to be the same length. So use Table to make it so.

{p, q} = {{x, y}, {a, b, c, d, e}}; MapThread[Append, {Table[p,Length[q]], q}]


Here is a very simple way to do it.

data = {{x, y}, {a, b, c, d, e}};
{data[[1, 1]], data[[1, 2]], #}& /@ data[[2]]


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

It's usually nice to have at least one method that preserves packed arrays, when the two lists in the input are packed arrays.

PadLeft[ArrayReshape[#2, {Length@#2, 1}], {Length@#2, 1 + Length@#1},
Reverse@#1] & @@ {{x, y}, {a, b, c, d, e}}
(*  {{x, y, a}, {x, y, b}, {x, y, c}, {x, y, d}, {x, y, e}}  *)

a1 = RandomInteger[9, 200];
a2 = RandomInteger[{100, 110}, 50000];

PadLeft[ArrayReshape[#2, {Length@#2, 1}], {Length@#2, 1 + Length@#1},
Reverse@#1] & @@ {a1, a2} // DeveloperPackedArrayQ
(*  True  *)


For fun, a couple of obscure ones, which make nice puzzles:

Through[(Append /@ #2)[#1]] & @@ {{x, y}, {a, b, c, d, e}}
(*  {{x, y, a}, {x, y, b}, {x, y, c}, {x, y, d}, {x, y, e}}  *)

Flatten@Level[Map @@ {{x, y}, {a, b, c, d, e}}, {2}, Heads -> True] ~Partition~ 3
(*  {{x, y, a}, {x, y, b}, {x, y, c}, {x, y, d}, {x, y, e}}  *)


With {p, q} = {{x, y}, {a, b, c, d, e}};

Table[Append[p, q[[i]]], {i, 1, Length@q}]


or

Outer[Join, {p}, Partition[q, 1], 1, 1][[1]]


or

Join[p, {#}] & /@ q
`

all give

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