0

For simplicity I'm try to do this.

spam = [1,2,3]
stuff = [spam]
x = input()
if x in stuff:
    print(True)
else:
    print(False)

As it runs:

>>> spam
False

Of course it doesn't print 'True' because the string 'spam' is not equal to the variable spam.

Is there a simple way of coding that I could check if the input is equal to the variable name? If not simple, anything?

user3213847
  • 113
  • 1
  • 3

4 Answers4

2

You should check the locals() and globals() dictionaries for the variable. These dictionaries have variable names as keys and their values.

spam = [1,2,3]
stuff = [spam]

x = raw_input()

if x in locals() and (locals()[x] in stuff) or \
   x in globals() and (globals()[x] in stuff):
    print(True)
else:
    print(False)

You can read more on locals() and globals().

ronakg
  • 4,038
  • 21
  • 46
1
>>> spam= [1,2,3]
>>> stuff = [spam]
>>> eval('spam') in stuff
True

DISCLAIMER : do this at your own risk.

heinst
  • 8,520
  • 7
  • 41
  • 77
C.B.
  • 8,096
  • 5
  • 20
  • 34
0

It's a weird idea to try and connect variable names with the world outside the program. How about:

data = {'spam':[1,2,3]}

stuff = [data['spam']]

x = raw_input()
if data[x] in stuff:
    print(True)
else:
    print(False)
TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87
  • You should do `data.get(x)` , if the user gets mischievous and enters a key that is not in the dictionary, your program would fail with `KeyError` – Anand S Kumar Jun 16 '15 at 19:09
0

isnt better to use:

data = {'spam':[1,2,3]} #create dictionary with key:value
x = input() # get input
print(x in data) #print is key in dictionary (True/False) you might use:
#print(str(x in data)) #- this will convert boolean type name to string value
vakus
  • 732
  • 1
  • 10
  • 24
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient [reputation](http://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](http://stackoverflow.com/help/privileges/comment). – skrilled Jun 16 '15 at 22:13
  • @skrilled It looks like an answer to me. A lot of problems are solved by taking a different approach than the OP originally thought. – o11c Jun 17 '15 at 00:55
  • Then the answer should elaborate on why it is proper instead of stating something equivalent to "why not try this" - shouldn't it? This attempt does not even begin to elaborate on why it would be a correct answer. – skrilled Jun 17 '15 at 19:44