6
$\begingroup$

I have these two lists, mylist = {{a,b},{c,d}}, and mysecondlist = {1,2}

I want to generate this output: output = {{{a,b,1},{a,b,2}},{{c,d,1},{c,d,2}}}

In other words, output[[1,1,1]] = {mylist[[1,1]],mysecondlist[[1]]}, output[[1,1,2]] = {mylist[[1,1]],mysecondlist[[2]]}, and so on. The original 2D list becomes a 3D one.

I'm not actually sure what the name of the operation is, let alone which command to use in Mathematica. Is there a command that generates this, or do I have to do it with a Do loop that runs over all the possible indices and defines them one by one?

$\endgroup$
9
$\begingroup$
Outer[Append, mylist, mysecondlist, 1]
{{{a, b, 1}, {a, b, 2}}, {{c, d, 1}, {c, d, 2}}}

Also

Outer[Join, mylist, List /@ mysecondlist, 1]

Flatten /@ Tuples[{{#},  mysecondlist}] & /@ mylist

Flatten /@ Thread[{#, mysecondlist}, List, {2}] & /@ mylist 

Distribute[{mylist, mysecondlist}, List, List, Partition[{##}, 2] &, Append]

all give

 {{{a, b, 1}, {a, b, 2}}, {{c, d, 1}, {c, d, 2}}}
$\endgroup$
6
$\begingroup$

My train of thought to tackle that problem would be the following:

Each of the elements of your desired solution has the elements of the second list appended.

I would first try to construct each element separately. The first element would be.

Append[{a, b}, #] & /@ mysecondlist

which gives

{{a, b, 1}, {a, b, 2}}

Afterwards I would replace {a,b} by a variable and use Map to obtain a list of all elements.

Function[{x}, Append[x, #] & /@ mysecondlist] /@ mylist

which gives

{{{a, b, 1}, {a, b, 2}}, {{c, d, 1}, {c, d, 2}}}

So in short: Try to divide the problem in smaller, easier solvable chunks.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.