# Combination of lists elementwise

I have two lists:

x = Range[1, 10, 1]
y = Range[2, 10, 2]


How can I produce a list consisting of the following elements (first element is the x value, second element the y value and third element some combination of it e.g. here the sum):

{
{x[[1]], y[[1]], x[[1]] + y[[1]]},
...
{x[[1]], y[[5]], x[[1]] + y[[5]]},
...
...
...
{x[[10]], y[[1]], x[[10]] + y[[1]]},
...
{x[[10]], y[[5]], x[[10]] + y[[5]]}
}

=

{
{1,2,3},
...
{1,10,11},
...
...
...
{10,2,12},
...
{10,10,20}
}

• Take a look at Table and may be Flatten afterwards Commented Nov 23, 2016 at 13:41
• Is this the only possibility?
– lio
Commented Nov 23, 2016 at 13:43
• No, you can also create first an empty list and fill it with AppendTo within a Do loop. Try it out :D Commented Nov 23, 2016 at 13:45

A more Mathematica-ish/functional approach than Do is as follows:

x = Range[1, 10, 1];
y = Range[2, 10, 2];
Flatten[Outer[{#1, #2, #1 + #2} &, x, y], 1]


Matrix multiplication is another option:

Tuples[{x, y}].{{1, 0, 1}, {0, 1, 1}}


As in the comments remarked, you can use Table as follows

x = Range[1, 10, 1];
y = Range[2, 10, 2];
t1 = Flatten[
Table[{x[[i]], y[[j]], x[[i]] + y[[j]]}, {i, Length@x}, {j, Length@y}]
,1]


{{1, 2, 3}, {1, 4, 5}, {1, 6, 7}, {1, 8, 9}, {1, 10, 11}, {2, 2,
4}, {2, 4, 6}, {2, 6, 8}, {2, 8, 10}, {2, 10, 12}, {3, 2, 5}, {3, 4,
7}, {3, 6, 9}, {3, 8, 11}, {3, 10, 13}, {4, 2, 6}, {4, 4, 8}, {4,
6, 10}, {4, 8, 12}, {4, 10, 14}, {5, 2, 7}, {5, 4, 9}, {5, 6, 11}, {5, 8, 13}, {5, 10, 15}, {6, 2, 8}, {6, 4, 10}, {6, 6, 12}, {6, 8, 14}, {6, 10, 16}, {7, 2, 9}, {7, 4, 11}, {7, 6, 13}, {7, 8, 15}, {7, 10, 17}, {8, 2, 10}, {8, 4, 12}, {8, 6, 14}, {8, 8, 16}, {8, 10, 18}, {9, 2, 11}, {9, 4, 13}, {9, 6, 15}, {9, 8, 17}, {9, 10, 19}, {10, 2, 12}, {10, 4, 14}, {10, 6, 16}, {10, 8, 18}, {10, 10, 20}}

or, for example, a Do loop

t2 = {};
Do[
AppendTo[t2, {x[[i]], y[[j]], x[[i]] + y[[j]]}]
, {i, Length@x}
, {j, Length@y}
]
t2 == t1


True

There are surely a lot of possibilities to do this.

• Thank you. Is instead of using loops also a solution with Map or ReplaceList possible?
– lio
Commented Nov 23, 2016 at 13:51
• performance tunning: point 3.2
– Kuba
Commented Nov 23, 2016 at 13:55
• Cool info! Thanks! Commented Nov 23, 2016 at 13:57

Also

{##, Plus@##} & @@@ Tuples[{x, y}]


Or

Distribute[{x, y}, List, List, List, {##, Plus@##} &]