Skip to content Skip to sidebar Skip to footer

Accessing A Local Variable Whose Name Comes From User Input

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:

Solution 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

Post a Comment for "Accessing A Local Variable Whose Name Comes From User Input"