# How can I merge two lists in a special way?

It's been over a year since I've used Mathematica, and I'm having a total brain fart on a home project. I'd like to take an existing list of lists, say,

x = {{1, 2}, {3, 4}, {5, 6}}


and append 9 and 10 onto the end of each sublist of x to get a list y, where

y = {{1, 2, 9}, {1 ,2, 10}, {3, 4, 9}, {3, 4, 10}, {5, 6, 9}, {5, 6, 10}}


I'm sure there's a built-in function to do this, but cannot recall it for the life of me.

-
Closely related: (13748) – Mr.Wizard Jul 15 '14 at 8:38

## 6 Answers

x = {{1, 2}, {3, 4}, {5, 6}};
y = {9, 10};
Flatten /@ Tuples[{x, y}]
(*
{{1, 2, 9}, {1, 2, 10}, {3, 4, 9}, {3, 4, 10}, {5, 6, 9}, {5, 6, 10}}
*)

-
Tuples. That was the function I had forgotten. – John Jan 22 '13 at 12:46

Another possibility using Outer:

x = {{1, 2}, {3, 4}, {5, 6}};
y = {9, 10};
Outer[# ~Join~ {#2} &, x, y, 1]


or

Outer[Flatten @ {##} &, x, y, 1]


Flatten the above result at level 1, if you want an output like in belisarius' answer.

-
+1. You could have used Outer[Append, x, y, 1] instead. – Leonid Shifrin Jan 22 '13 at 10:11
@Leonid It's a little trick I learned... people have an irrational dislike of Append ("eeek! don't use AppendTo to grow a list", etc.), but not Join, although they both do the same thing (and are equally "problematic"). So the less one uses it in an answer, the better the chances of an upvote =) "Irrational" was probably the wrong word, because it is completely justified, but what I really mean is that the dislike is attached to the word rather than to what it does (or how). Of course, a +1 comment from you increases the chances of trickle down upvotes much more, so it's a net win :D – R. M. Jan 23 '13 at 20:38
Flatten /@ Distribute[{x, {9, 10}}, List]


=> {1, 2, 9}, {1, 2, 10}, {3, 4, 9}, {3, 4, 10}, {5, 6, 9}, {5, 6, 10}}

-

Update: ... forgot Table!!

 Join @@ Table[Flatten@{i, j}, {i, x}, {j, y}]


or, with the new-in-Version-9 ArrayReshape,

 ArrayReshape[Table[{i, j}, {i, x}, {j, y}], {6, 3}]
(* {{1, 2, 9}, {1, 2, 10}, {3, 4, 9}, {3, 4, 10}, {5, 6, 9}, {5, 6, 10}} *)


Join @@ (PadRight[x, {1 + Length@First@x, Length@x}, #] & /@ y) // Sort
(* {{1, 2, 9}, {1, 2, 10}, {3, 4, 9}, {3, 4, 10}, {5, 6, 9}, {5, 6, 10}} *)


or

Distribute[Append[{x}, y], List, List, List, Append]
Distribute[{x, y}, List, List, List, Append]

-

Some I wrote before reading other answers, from shortest to longest:

x = {{1, 2}, {3, 4}, {5, 6}};

Append @@@ Tuples @ {x, {9, 10}}

Join @@ Outer[Append, x, {9, 10}, 1]

Flatten[{{##, 9}, {##, 10}} & @@@ x, 1]

Join @@ Thread /@ ArrayFlatten@{{x, {9, 10}}}

Join @@ Table[a ~Append~ b, {a, x}, {b, {9, 10}}]


And I just thought of:

## &[{##, 9}, {##, 10}] & @@@ x

-

Just to be different:

MapIndexed[#1~Join~(10 - Mod[#2, 2]) &, Riffle[x, x]]
Join @@@ Riffle[Riffle[x, x], {{9}, {10}}, {2, -1, 2}]~Partition~2
(*{{1, 2, 9}, {1, 2, 10}, {3, 4, 9}, {3, 4, 10}, {5, 6, 9}, {5, 6, 10}}*)

-