Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm looking to access variables in different contexts. The contexts are stored in a list labeled contexttable. Each context, of course, is a string. Is there any way, without using NotebookWrite, to access a variable of the same name, say x, in each context?

I am looking for something like

 contexttable = {"Context1`", "Context2`", ..., "ContextN`"};
 Map[Print[# <> x]&, contexttable]

which would print the x variable in each context.

share|improve this question
Look up Symbol or ToExpression in the docs. Be aware that if the variable you reference does not exist, you will create a new symbol by using those. – Leonid Shifrin Mar 29 '13 at 22:13
up vote 1 down vote accepted

As Leonid Shifrin said in his comment, you can use SymbolName and ToExpression to get the values in each context.

{Context1`x, Context2`x} = {"foo", 42}; 
contexttable = {"Context1`", "Context2`", "Context3`"};
ToExpression[# <> SymbolName @ Unevaluated @ x] & /@ contexttable

{"foo", 42, Context3`x}

share|improve this answer

Also following Leonid's comment, and borrowing from m_goldberg's answer, if you wish to avoid creating new symbols you can use Names to filter before passing to Symbol:

{Context1`x, Context2`x} = {"foo", 42};
contexttable = {"Context1`", "Context2`", "Context3`"};

Symbol /@ Names[# <> "x" & /@ contexttable]
{"foo", 42}

Here Context3`x is never created and only the values for Symbols that exist are returned. This may or may not be desirable. If creation of new Symbols is desired just leave out Names:

Symbol[# <> "x"] & /@ contexttable
{"foo", 42, Context3`x}

Note that in each case the symbol name is given as a string, which greatly simplifies things.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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