One can create new variable names by Symbol :

In[1]  Table[Symbol["x"<>ToString[i]], {i,1,5}]
Out[1]  {x1,x2,x3,x4,x5}

But it is also possible to use ToExpression (old firend) :

In[2]  Table[ToExpression["x"<>ToString[i]], {i,1,5}]
Out[2]  {x1,x2,x3,x4,x5}

There is a difference : Symbol will produce an error for incorrect varialbe names while ToExpression will do something meaningful.

In[3]  Table[Symbol[ToString[i]<>"x"], {i,1,5}]
Out[3]  (* some error message with non-helpful output)

In[4]  Table[ToExpression[ToString[i]<>"x"], {i,1,5}]
Out[4]  {x,2x,3x,4x,5x}

Other than this, I see there is no difference. Is there a situation such that Symbol is more useful than ToExpression ?

  • 1
    $\begingroup$ well if you want to make sure you have a variable name at the end, Symbol lets you Check for the error and do something different instead! $\endgroup$
    – thorimur
    Jul 25 at 2:56
  • 2
    $\begingroup$ ToExpression["foo", StandardForm, Hold] can be useful. $\endgroup$
    – Michael E2
    Jul 25 at 2:56
  • $\begingroup$ Thank you both answeres! @Michael E2 : The code always generates Hold[foo] when even foo has a value. $\endgroup$
    – imida k
    Jul 25 at 6:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.