Assigning each string variable to the corresponding element from the list inside a loop

I would like to assign values from a list l to variables g1, g2, g3, ....

The list: l=Table[(i^2-10*i)/2,{i,1,10}].I would like to assign g1 to the first element of the list l[[1]] and so on using a loop.

g1=l[[1]];
g2=l[[2]];
g3=l[[3]];
...

ClearAll["Global*"]

l = Table[(i^2 - 10*i)/2, {i, 1, 10}]

(*{-(9/2), -8, -(21/2), -12, -(25/2), -12, -(21/2), -8, -(9/
2), 0}*)

Do[Symbol["g" <> ToString[i]] = l[[i]], {i, 1, 10}]


How to do it correctly?

• Based on your last three questions, it appears that you're trying to do some computations with lists of things, and you think you need variables to represent each thing. Or something along those lines. Maybe if you just told us the problem you're trying to solve, we could give you good advice. I'm starting to feel bad about answering your specific questions, because they will ultimately lead you to bad programming practices. May 18 at 16:41
• May 18 at 17:04
• @lericr, thanks a lot! Yes, you're right, it's worth setting variables more obviously. May 18 at 17:29
• @evanb, thanks for the link! May 18 at 17:29

This question is very likely an XY problem.

I'd say the "correct" way is to avoid symbol construction through strings, and go with indices instead. Using a delayed assignment,

Clear[g];
g[i_Integer /; 1 <= i <= Length[l]] := l[[i]]
g[___] = Indeterminate;


or, if you don't care about error checking,

Clear[g];
g[i_] := l[[i]]


You can use g[5] instead of your g5, for example, without affecting calculations.

• Thanks! But how to set such variables g[5] in a function f? I mean for example f[g[5]_]:=g[5]^2 May 18 at 16:34
• Just say something like f[x_]:=g[x]^2? May 18 at 17:06
• Or, just l^2, even. May 18 at 17:06
• You need to learn more about what variables and patterns are. As @evanb says, define f[x_] = x^2 and then call f[g[5]] because it will substitute the pattern x_ with the argument g[5]. There is really no need to define a new function f` for every variable you have. May 18 at 17:40
• @Roman, thanks! May 18 at 18:15