6
$\begingroup$
ClearAll[x, f]
x = {a, b, c};
f = {3, 5, 2};
Thread[Table[x, f]]

produces

Table::nliter: Non-list iterator f at position 2 does not evaluate to a real numeric value.

Table[x, f]

Why can't I create {a,a,a,b,b,b,b,b,c,c} from x={a,b,c}; f={3,5,2}; Thread@Table[x,f]?

However, the following is fine!

ClearAll[x, f]
x = {a, b, c};
f = {3, 5, 2};
MapThread[Table, {x, f}]

Note: //Flatten at the end is intentionally removed for simplicity.

$\endgroup$
13
$\begingroup$

This is an evaluation order issue.

  • x and f need to expand (evaluate) to {a, b, c} and {3, 5, 2} for Thread to work
  • Table has attribute HoldAll which prevents its arguments form evaluating first
  • Specific evaluation of Table (before Thread) should be suppressed to avoid warning messages

Holding Table gets around each of these points:

x = {a, b, c};
f = {3, 5, 2};

Thread[Hold[Table][x, f]] // ReleaseHold
{{a, a, a}, {b, b, b, b, b}, {c, c}}

Similarly using Inactive/Activate:

Thread[Inactive[Table][x, f]] // Activate
{{a, a, a}, {b, b, b, b, b}, {c, c}}

But it is usually easier to Apply afterward:

Table @@@ Thread[{x, f}]
{{a, a, a}, {b, b, b, b, b}, {c, c}}

Consider also Inner

Inner[Table, x, f, Join]
{a, a, a, b, b, b, b, b, c, c}
| improve this answer | |
$\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.