5

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.

b3m2a1
  • 46,870
  • 3
  • 92
  • 239
Chris Nadovich
  • 509
  • 2
  • 11

3 Answers3

8

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}

Carl Woll
  • 130,679
  • 6
  • 243
  • 355
7

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.

ktm
  • 4,242
  • 20
  • 28
3

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}
Michael E2
  • 235,386
  • 17
  • 334
  • 747