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?

2

4 Answers 4

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().

Sign up to request clarification or add additional context in comments.

Comments

1
>>> spam= [1,2,3]
>>> stuff = [spam]
>>> eval('spam') in stuff
True

DISCLAIMER : do this at your own risk.

Comments

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)

1 Comment

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

3 Comments

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 you will be able to comment on any post.
@skrilled It looks like an answer to me. A lot of problems are solved by taking a different approach than the OP originally thought.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.