I'm writing a function that constructs a multidimensional array (that is, nested lists) using Table. The dimension of the array varies according to the argument to the function, so the number of arguments to Table will vary. So I use Sequence to provide some of the arguments to Table. But it fails, and I see a weird behavior.

For example, if I type the code

    Table[{i, j}, {i, 3}, {j, 4}]

then I get

    {{{1, 1}, {1, 2}, {1, 3}}, {{2, 1}, {2, 2}, {2, 3}}}

Now, I'm trying to provide all but the first argument to Table dynamically, so I use Sequence. I try it first on an expression with the head "Table" replaced by something undefined, just to make sure that the arguments are evaluated correctly.

    SomeHead[{i, j}, Sequence @@ MapThread[List, {{i, j}, {3, 4}}]]

evaluates to

    SomeHead[{i, j}, {i, 3}, {j, 4}]

which is identical to the first code I wrote here, except with the head Table replaced with the undefined symbol Somehead. But if I now write

    Table[{i, j}, Sequence @@ MapThread[List, {{i, j}, {3, 4}}]]

which should give the first result above, it instead gives an error:

    Table::nliter: Non-list iterator Sequence@@MapThread[List,{{i,j},{3,4}}] at position 2 does not evaluate to a real numeric value.
    Table[{i, j}, Sequence @@ MapThread[List, {{i, j}, {3, 4}}]]

Why is this happening? And how can I write Table with dynamic number of arguments?


1 Answer 1


{HoldAll, Protected}

HoldAll is a problem because it prevents your Sequence from being evaluated before Table is evaluated.

You could insert Evaluate or use Apply:

Table[{i, j}, Evaluate[Sequence @@ MapThread[List, {{i, j}, {3, 4}}]]]
Table[{i, j}, ##] & @@ MapThread[List, {{i, j}, {3, 4}}]
{{{1, 1}, {1, 2}, {1, 3}, {1, 4}},  
 {{2, 1}, {2, 2}, {2, 3}, {2, 4}},  
 {{3, 1}, {3, 2}, {3, 3}, {3, 4}}}
  • $\begingroup$ Thank you very much! :D $\endgroup$ Mar 28, 2018 at 11:39
  • 1
    $\begingroup$ I personally prefer the second version; it's usually less confusing to do. $\endgroup$ Mar 28, 2018 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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