Suppose I defined a number of variables in a cell, in the Notebook interface. I know the number of this cell (In[296], for example). Is there a way to clear all the variables defined in this input (In[296])?

  • $\begingroup$ In general no. How would you parse x = ToExpression["y = 2"] vs x = Hold@ToExpression["y = 2"]? $\endgroup$
    – Kuba
    Sep 13, 2017 at 9:42
  • $\begingroup$ So it will be very complicated to parse it correctly, unless you narrow your case down to e.g. list of separate lines with simple assignments. $\endgroup$
    – Kuba
    Sep 13, 2017 at 9:54

1 Answer 1


Not much information has been given on the type of assignments so this solution just targets Set assignments.

Collect the Cell from its CellLabel .

{c} = Cells[CellLabel -> "In[296]:="]

Then collect assignment variables at all levels and ClearAll the variables.

ClearAll[#] & /@ 
  Cases[NotebookRead[c], HoldPattern[RowBox[{sym_, "=", _}]] :> sym, 

Hope this helps.

  • $\begingroup$ Probably NotebookImport can help. $\endgroup$ Sep 13, 2017 at 10:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.