Finding a variable name given its numerical value

9

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}?

S. Lee

Posted 2018-02-16T22:51:05.180

Reputation: 91

What if you had typed x = 3; y = 7; z = 3;, what would you expect to get back by then typing {3,7}? – Jason B. – 2018-02-16T22:53:45.057

@S.Lee does my answer fit your needs? – Kuba – 2018-02-21T12:01:09.517

Answers

13

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"}

Kuba

Posted 2018-02-16T22:51:05.180

Reputation: 129 207