# Apply Clear puzzle

This is OK

foo=1; bar=2;
Clear[foo,bar]

But this is not

foo=1; bar=2;
Clear@@{foo,bar}

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.

• In that case, just use SetAttributes[clear, HoldAll]; clear[{a__}] := Clear[a]. Commented Jan 23, 2018 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}
• This is BY FAR the best answer to my question. Commented Feb 7, 2018 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

foo
bar

foo

bar

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}

• The problem is that what I want to delete is a list of symbols, not a list of names. Commented Jan 23, 2018 at 22:38
• This isn't the best answer to my question, even though it got the most up votes. Commented Feb 7, 2018 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.

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