# Make a nested list of variable size

I want to try to make a list of lists of variable length in the following way

varNames = Table[Subscript[x, i], {i, 1, dim}]
varRange = Table[{varNames[[i]], 1, maxRange}, {i, 1, Length[varNames]}]

Flatten[ Table[varNames, varRange], dim -1]


Here, the variables dim and maxRange are arbitrary, and I will be setting them depending on the situation.

This does not work, because

a) The Table function gives the error

Non-list iterator varRange at position 2 does not evaluate to a real numeric value.


b) The would-be iterator needs to lose it's last set of brackets, i.e.

{{x1, 1, 4}, {x2, 1, 4}, {x3, 1, 4}}


needs to be

{x1, 1, 4}, {x2, 1, 4}, {x3, 1, 4}


Ideally, for dim=3 and maxRange=4, I want to get something like

varNames = {x1, x2, x3}
varRange = {{x1, 1, 4}, {x2, 1, 4}, {x3, 1, 4}}


and the instruction would be to create a list of lists in the following way

Flatten[Table[{x1, x2, x3}, {x1, 1, 4}, {x2, 1, 4}, {x3, 1, 4} ], 2]


Is there a way to fix this or a simpler way to do what I want?

• Your last line generates a list of numbers {{1, 1, 1}, {1, 1, 2}, {1, 1, 3}, {1, 1, 4}, {1, 2, 1}, {1, 2, 2}, {1,2, 3}, {1, 2, 4}...., i.e. Tuples[Range, 3]. Is that what you intend? Or are you looking for a list of variable names? – MelaGo Jul 10 '19 at 18:29
• Yes, this is what I intend. I'm actually trying to avoid using Tuples[ ] because I am dealing with a large length (order 100 and above) list and Tuples causes the kernel to quit. I find that using Table[] this way avoids crashing Mathematica. – nonreligious Jul 10 '19 at 18:34
• 4^100 elements is more than the number of particles in the observable universe; are you sure this is the list you want to create? – lirtosiast Jul 10 '19 at 19:00
• Sorry, maybe I mis-wrote what I meant but it would be more 100^4, or 100^6. – nonreligious Jul 10 '19 at 19:01

I found what I think might be a solution to this, in an answer to another question, here.

dim = 4;
varNames = Table[Subscript[x, i], {i, 1, dim}]
varRange = Table[{varNames[[i]], 1, 100}, {i, 1, Length[varNames]}]
a = Flatten[Table[varRange[[All, 1]], ##] & @@ varRange, dim - 1]


This makes use of the slot sequence ## which hurts my head to think about.

Still takes a while, and I can't monitor what's going inside the iteration to create the table. And still takes up a lot of memory.

Can this be improved upon?