# How to create a flat Table

Is there any function to directly create a flat list of expressions as a function of multiple index variables, in other words a flat version of Table. What I mean is to have for example

flatTable[expr[a,b],{a,1,3},{b,7,8}]


output a list

{expr[1,7],expr[1,8],expr[2,7],expr[2,8],expr[3,7],expr[3,8]}

(or perhaps in a different order). Note that expr[i,j] could be a List (or a list of lists etc).

One solution seems to be:

flatTable[expr_,indices__]:=Flatten[#,{Range[Length[{indices}]]}]&@Table[expr,indices]


but there must be a better way.

• Look at Tuples. For instance, expr @@@ Tuples[{{1, 2, 3}, {7, 8}}]. – MarcoB Jun 13 '18 at 12:52
• flatTable = Join @@ Table[##] &? – kglr Jun 13 '18 at 13:07
• Probably the shortest version: Flatten@*Table – Wjx Jun 13 '18 at 14:46
• @Wjx, what did you mean with the star? (If you meant Flatten@Table then it of course does not work if the expression in the table already has a list structure.) – Kvothe Jun 13 '18 at 16:20
• @Kvothe that is Composition ~ which is almost identical to Flatten[Table[##]]& – Wjx Jun 14 '18 at 10:48

ClearAll[flatTable]
flatTable = Flatten[Table@##, Length[{##2}] - 1] &;


Examples:

flatTable[expr[a, b], {a, 1, 3}, {b, 7, 8}]


{expr[1, 7], expr[1, 8], expr[2, 7], expr[2, 8], expr[3, 7], expr[3, 8]}

flatTable[expr[a, b, c], {a, 1, 3}, {b, 7, 8}, {c, 5, 6}]


{expr[1, 7, 5], expr[1, 7, 6], expr[1, 8, 5], expr[1, 8, 6], expr[2, 7, 5], expr[2, 7, 6], expr[2, 8, 5], expr[2, 8, 6], expr[3, 7, 5], expr[3, 7, 6], expr[3, 8, 5], expr[3, 8, 6]}

• thanks. This is basically in the spirit of the solution I included myself. But it is a good lesson to see how I could have written it slightly cleaner / more compact. – Kvothe Jun 13 '18 at 13:21