# Unset variable by its name given as a string

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:

Given:

x = 10;


trying to unset later:

Unset[Symbol["x"]]


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.

-
Dumb solution: ToExpression["Unset[" <> "x" <> "]"]. –  Ｊ. Ｍ. May 7 '13 at 12:27

You can use the third argument of ToExpression to do this in a structured way:
ToExpression["x", InputForm, Unset]

+1. I remember that you have a long history of using this construct, which I also use often. @sakra An alternative: Unset @@ ToHeldExpression["x"] –  Leonid Shifrin May 7 '13 at 16:47
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. –  Szabolcs May 7 '13 at 16:56
@Szabolcs ToHeldExpression is deprecated and undocumented, but I am sure it will stay. –  Leonid Shifrin May 7 '13 at 17:40
As noted here, ToHeldExpression[] was deprecated in version three. Still, it remains in the kernel, much like that other function Release[]... –  Ｊ. Ｍ. May 7 '13 at 20:51