# Producing a list of all the pairs can be made by from two lists of equal length [closed]

I have two lists:

{x1, x2, x3, x4, x5}


and

{y1, y2, y3, y4, y5}


How can I get a list like the one below from them, where each element in the first list is paired with each element in the second?

{{x1, y1}, {x1, y2}, {x1, y3}, ..., {x2, y1}, {x2, y2}, ..., {x5, y5}}

Can I avoid using Table to do it?

• Outer is made for this. Here, Outer[List, xlist, ylist] does the job. Commented Nov 24, 2016 at 11:13

Use Tuples:

Tuples[{{x1, x2, x3, x4, x5} , {y1, y2, y3, y4, y5}}]
(* {{x1, y1}, {x1, y2}, {x1, y3}, {x1, y4}, {x1, y5}, {x2,
y1}, {x2, y2}, {x2, y3}, {x2, y4}, {x2, y5}, {x3, y1}, {x3,
y2}, {x3, y3}, {x3, y4}, {x3, y5}, {x4, y1}, {x4, y2}, {x4,
y3}, {x4, y4}, {x4, y5}, {x5, y1}, {x5, y2}, {x5, y3}, {x5,
y4}, {x5, y5}} *)


Can I avoid using Table to do it?

Actually I don't think Table is bad for this if you use the right syntax. I don't think it's any worse than Outer.

xx = {x1, x2, x3, x4, x5};

yy = {y1, y2, y3, y4, y5};

Table[{x, y}, {x, xx}, {y, yy}]
(* {{{x1, y1}, {x1, y2}, {x1, y3}, {x1, y4}, {x1, y5}}, {{x2,
y1}, {x2, y2}, {x2, y3}, {x2, y4}, {x2, y5}}, {{x3, y1}, {x3,
y2}, {x3, y3}, {x3, y4}, {x3, y5}}, {{x4, y1}, {x4, y2}, {x4,
y3}, {x4, y4}, {x4, y5}}, {{x5, y1}, {x5, y2}, {x5, y3}, {x5,
y4}, {x5, y5}}} *)

Catenate[%]
(* {{x1, y1}, {x1, y2}, {x1, y3}, {x1, y4}, {x1, y5}, {x2,
y1}, {x2, y2}, {x2, y3}, {x2, y4}, {x2, y5}, {x3, y1}, {x3,
y2}, {x3, y3}, {x3, y4}, {x3, y5}, {x4, y1}, {x4, y2}, {x4,
y3}, {x4, y4}, {x4, y5}, {x5, y1}, {x5, y2}, {x5, y3}, {x5,
y4}, {x5, y5}} *)


There are lots of ways you could achieve this result: the Outer function is probably easiest. For example,

xlist={x1,x2,x3,x4,x5};ylist={y1,y2,y3,y4,y5};
result=Outer[{#1,#2}&,xlist,ylist]


This will have extra layers of braces relative to the output you want: you could get rid of them by applying Flatten[result,1].

• Suggest Outer[{#1, #2} &, xlist, ylist] // Catenate, rather than Flatten. Commented Nov 24, 2016 at 12:51
• @m_goldberg In older versions Catenate is slower than Join @@ on packed arrays. (I was surprised when people told me about this.) Not sure about Flatten[..., 1]. I do prefer the Catenate syntax. Commented Nov 24, 2016 at 12:55