1

i need to access strings using raw_input.

list1 = ["one","Two","three"]

list2 = ["1","2","3"]

while True:

        ip = raw_input("enter list: ")
        for i  in  ip:
                    print i
        break

When "list1" is given as input, it takes as string but not as list. I need to access the list defined above. I need a way to access the lists and print the list.

5
  • 1
    I think that what you are describing is eval. Commented Dec 18, 2014 at 0:23
  • eval using user-supplied data == bad bad bad idea Commented Dec 18, 2014 at 0:33
  • You should not use eval instead of that use literal eval. stackoverflow.com/questions/15197673/… Commented Dec 18, 2014 at 0:34
  • @TanveerAlam: even literal_eval with user supplied input can be bad for security (in the best case leak a lot of information). Commented Dec 18, 2014 at 0:37
  • I wanted to make sure that they use literal eval instead of eval but in this case that is bad idea. Thanks Paulo. Commented Dec 18, 2014 at 0:41

1 Answer 1

1

Use a dict:

lists = {
    "list1": ["one","Two","three"],
    "list2": ["1","2","3"],       
}

while True:
    choice = raw_input("enter the list name: ")
    try:
        for item in lists[choice]:
            print item
    except KeyError:
        print "I never heard of any list named '{}'! Try again.".format(choice)
    else:
        break
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Paulo for the 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.