This is OK

foo=1; bar=2;

But this is not

foo=1; bar=2;

Clear::ssym: 1 is not a symbol.
Clear::ssym: 2 is not a symbol.

So how do you Clear a list of symbols?

I understand that clearing a list of strings that name those symbols, as in This answer is possible. But that's not what I'm asking.

  • 2
    $\begingroup$ In that case, just use SetAttributes[clear, HoldAll]; clear[{a__}] := Clear[a]. $\endgroup$ – Carl Woll Jan 23 '18 at 22:50

I'm not sure how you have an unevaluated list of symbols that values, but you can use Unevaluated to keep it that way:

foo = 1; bar = 2;
Clear @@ Unevaluated@{foo, bar}
  • $\begingroup$ This is BY FAR the best answer to my question. $\endgroup$ – Chris Nadovich Feb 7 '18 at 14:18

I would store a list of the variable symbol names instead of the symbols:

vlist = {"foo", "bar"};

foo = 1; bar = 2;
Clear @@ vlist




If you are copy/pasting the list of symbol names, then I think the following function would be simplest:

SetAttributes[clear, HoldAll]
clear[{a__}] := Clear[a]

x=2; y=2; z=2;
clear[{x, y, z}]

{x, y, z}

{x, y, z}

  • $\begingroup$ The problem is that what I want to delete is a list of symbols, not a list of names. $\endgroup$ – Chris Nadovich Jan 23 '18 at 22:38
  • $\begingroup$ This isn't the best answer to my question, even though it got the most up votes. $\endgroup$ – Chris Nadovich Feb 7 '18 at 14:19

Note that this is happening in your code because by the time Clear gets to the variables, List ({}) has evaluated them and Clear tries to operate on 1 and 2, which is of course nonsense.

Consider the clearList function here:

In[1]:= x = y = z = 2;

In[2]:= clearList[lis_List] := 
 ReleaseHold[Map[Clear, HoldComplete[lis], {2}]]
SetAttributes[clearList, HoldFirst]

In[5]:= {x, y, z}

Out[5]= {2, 2, 2}

In[6]:= clearList[{x, y, z}]

Out[6]= {Null, Null, Null}

In[7]:= {x, y, z}

Out[7]= {x, y, z}

This is what I use, there may be better ways to do it.

  • $\begingroup$ I understood why, I just didn't know how to fix it. Thanks for the excellent answer. $\endgroup$ – Chris Nadovich Jan 23 '18 at 22:43
  • $\begingroup$ I’d like to add that Carl gave a more succinct version of this in the comments above. Same effect though. $\endgroup$ – user6014 Jan 24 '18 at 4:53

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.