9
$\begingroup$

If I set up

a = 1

Is there any command to get "a" by typing value 1?

Another example.

If

x = 3

y = 7

z = 6

then, Can I get 'xyz' by typing something like {3,7,6}?

$\endgroup$
2
  • $\begingroup$ What if you had typed x = 3; y = 7; z = 3;, what would you expect to get back by then typing {3,7}? $\endgroup$
    – Jason B.
    Commented Feb 16, 2018 at 22:53
  • $\begingroup$ @S.Lee does my answer fit your needs? $\endgroup$
    – Kuba
    Commented Feb 21, 2018 at 12:01

1 Answer 1

13
$\begingroup$
a = 1;

Select[Names["Global`*"], Symbol[#] == 1 &]
{"a"}

Notice it may not be robust if you have a habit of writing procedures with OwnValues, e.g.: c := NotebookClose @ EvaluationNotebook[] etc.

ClearAll[a]
a := Echo["this is only echo but it may be something more damaging"];
b = 1;

Select[Names["Global`*"], Symbol[#] == 1 &]
>> this is only echo but it may be something more damaging

{"b"}

To avoid this you can scan OwnValues instead of using Symbol/ToExpression:

Select[
  Names["Global`*"]
, ToExpression[
    #
  , StandardForm
  , Function[sym, MemberQ[OwnValues[sym], _ :> 1], HoldFirst]
  ] &
]
{"b"}
$\endgroup$

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.