16

What is the difference between Remove and ClearAll?

I thought that "not being recognized by Mathematica", which is the effect of Remove, meant that there would be no "values, definitions, attributes, messages, and defaults associated with symbols", which is the effect of ClearAll. That naive equivalence is wrong as shown by the different output out of these two lines:

b := a; Remove[a]; b
b := a; ClearAll[a]; b

Which side effects of Remove are not shared by ClearAll (and viceversa)?

Kuba
  • 136,707
  • 13
  • 279
  • 740
Hector
  • 6,428
  • 15
  • 34

2 Answers2

20

ClearAll clears all definitions associated with the symbol. However, the symbol remains in the symbol table, so all references to that symbol from other symbols (their definitions) remain fully valid. The symbol can then acquire new rules or other global properties associated with it.

Remove removes the symbol from the symbol table. More precisely, it removes the association between the symbol name and the actual symbol. In any case, the symbol becomes unusable (normally. There are ways to still use it, will mention that below). The same is true for all references to that symbol from other symbols, which silently become invalid. What this means is that by using Remove, one can subtly invalidate the code in ways which will be very hard to track (but see the link below for some suggestions here). For more details on certain interesting properties of Remove-d symbols, I refer to this discussion.

In terms of their usage, the two functions are quite different. ClearAll is a function intended for quite frequent and general use. Remove, however, I view as a much more specialist and lower-level function. In fact, I would advise against using Remove unless you know exactly what you are doing. It does have a number of advanced uses, but normally the only use which comes to mind is to remove an accidental shadow symbol during the interactive work.

Leonid Shifrin
  • 114,335
  • 15
  • 329
  • 420
10

Besides destroying the symbol itself, the main side effect of Remove that is not shared by ClearAll is what happens to expressions containing a removed symbol.

a = {x, y};
ClearAll[x, y];a
{x, y} 
Remove[y]; a  
{x, Removed[y]}
m_goldberg
  • 107,779
  • 16
  • 103
  • 257