Search code examples
pythonarraysinputconcatenation

How to refer an input to a list, and then refer to the list using the inputted variable | PYTHON


How would I go about using a user input to refer to a list, and then continuing to use this user input to refer to the list.

For example:

list1 = [6,23,9]
list2 = ["book","tree","car"]
getlist = input("Enter list: ")
print(getlist[0])

This code will just print the first letter of the input, but how would I make it print the first index of the inputted list. For example if I input list2, how will I get the input 'book' rather than 'l'. Many thanks.


Solution

  • There's no good way to map user input to actual variable names.

    Use a dictionary instead, where the top-level keys are the list names.

    data = {
        "list1": [6,23,9],
        "list2": ["book","tree","car"],
    }
    
    name = input("Enter list: ")
    print(data[name][0])