Unlike the function Clear, the function Unset does not work for string patterns. Given the name of a variable as a string, how can you unset the corresponding variable? Example:


x = 10;

trying to unset later:


results in

Unset::write: Tag Symbol in Symbol[x] is Protected. >>

Using With:

With[{var = Symbol["x"]}, Unset[var]]

results in

Unset::usraw: Cannot unset raw object 10. >>

Note that Clear["x"] is not an option, because it also removes all DownValues associated with x.

  • 2
    $\begingroup$ Dumb solution: ToExpression["Unset[" <> "x" <> "]"]. $\endgroup$ – J. M.'s ennui May 7 '13 at 12:27
  • $\begingroup$ ToExpression@MakeBoxes[RawBoxes["x"] =.] $\endgroup$ – Kuba May 13 '15 at 12:37

You can use the third argument of ToExpression to do this in a structured way:

ToExpression["x", InputForm, Unset]
  • $\begingroup$ That's a tricky solution! Thanks. $\endgroup$ – sakra May 7 '13 at 13:00
  • 1
    $\begingroup$ +1. I remember that you have a long history of using this construct, which I also use often. @sakra An alternative: Unset @@ ToHeldExpression["x"] $\endgroup$ – Leonid Shifrin May 7 '13 at 16:47
  • 1
    $\begingroup$ Yes, it's useful when trying to do something with some symbols I get from Names["...*"]. The usual form one ends up with is ToExpression["x", InputForm, Function[expr, ..., {HoldAll}]], which is rather cumbersome. I did not know about ToHeldExpression. It might make some things simpler. $\endgroup$ – Szabolcs May 7 '13 at 16:56
  • $\begingroup$ @Szabolcs ToHeldExpression is deprecated and undocumented, but I am sure it will stay. $\endgroup$ – Leonid Shifrin May 7 '13 at 17:40
  • $\begingroup$ As noted here, ToHeldExpression[] was deprecated in version three. Still, it remains in the kernel, much like that other function Release[]... $\endgroup$ – J. M.'s ennui May 7 '13 at 20:51

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.