Message Boards Message Boards

0
|
5092 Views
|
4 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Assign values to a list of variables

Suppose I have a list of variables:

vlist={a,b,c}

I want to set a=1, b=2, c=3, but the following doesn't work:

vlist={1,2,3}

After the previous statement, vlist = {1,2,3} but the values of a, b, and c are unassigned.

Of course the following is trivial:

{a,b,c}={1,2,3}

but I want the variables contained in vlist to be selected programatically.

Can anyone suggest a path forward?

POSTED BY: John Shonder
4 Replies

Hello John,

I guess one sees this effect because Set has the attribute HoldFirst - for obvious reasons! Consequently you can do it simply like so:

Remove[a, b, c, vlist];
vlist = {a, b, c};
Evaluate[vlist] = {1, 2, 3}
POSTED BY: Henrik Schachner
Posted 4 years ago

Hi John,

Maybe

Remove[a, b, c, vlist];
vlist = Unevaluated /@ {a, b, c};

MapThread[Set, {vlist, {1, 2, 3}}];

{a, b, c}
(* {1, 2, 3} *)
POSTED BY: Rohit Namjoshi

Thank you Rohit, this works.

POSTED BY: John Shonder

Maybe

With[{v = vlist}, v = Range[3]]
POSTED BY: Shenghui Yang
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract