Generate list of strings from a list of assigned variables

Here's a way:

var1 = 10;
var2 = 11;
var3 = 17;
var4 = 5;
compvar := {var1, var2, var3, var4}
compvar; (*all variables assigned*)

ClearAll[f];
SetAttributes[f, {HoldAll}];
f[x_, y__] := Flatten@{f[x], f[y]}
f[x_] := SymbolName@Unevaluated@x

OwnValues[compvar] /. {HoldPattern[y_] :> {x__}} :> f[x]

(*
 {"var1", "var2", "var3", "var4"}
*)

You must introduce some form of holding in you definition of compvar as otherwise, assuming it is defined after var1, var2, etc., there is no information to retrieve:

var1 = 10;
var2 = 11;
var3 = 17;
var4 = 5;

compvar = {var1, var2, var3, var4};

Definition[compvar]
compvar = {10, 11, 17, 5}

You could use Hold but then you would need to ReleaseHold (or similar) every time you used compvar. Instead I suggest you use SetDelayed and then recover the definition using my step function from:

  • How do I evaluate only one step of an expression?

It returns an expression wrapped in HoldForm:

compvar := {var1, var2, var3, var4};

step[compvar] // InputForm
HoldForm[{var1, var2, var3, var4}]

To convert to a list of strings:

Cases[step[compvar], s_Symbol :> SymbolName @ Unevaluated @ s, {2}]
{"var1", "var2", "var3", "var4"}

Or:

StringSplit[ToString @ step[compvar], ("{" | "," | " " | "}") ..]
{"var1", "var2", "var3", "var4"}

The first method will return Symbols (as strings) only while the second will convert other expressions as well.


Incidentally if you do not need to store your Symbols in a List you could use a more direct form:

compHeld = Hold[var1, var2, var3, var4];

List @@ SymbolName /@ Unevaluated /@ compHeld
{"var1", "var2", "var3", "var4"}

one way is to make a replacement rule seperately and use that.

Clear[var1, var2, var3, var4];
vars = {var1, var2, var3, var4};
values = {var1 -> 10, var2 -> 11, var3 -> 17, var4 -> 5};
compvar = vars /. values

Mathematica graphics

compvarstr = ToString[#] & /@ vars
FullForm[compvarstr]

Mathematica graphics

Otherwise, the way you had it:

 var1 = 10; var2 = 11; var3 = 17; var4 = 5;
 compvar = {var1, var2, var3, var4}; (*all variables assigned*)

Now the var1 name itself is replaced by 10 right away by the evaluator. Hence compvar will always be {10, 11, 17, 5} and the name of the variables is not known inside compvar since their value is used.