0

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.

FireFin
  • 5
  • 5
  • `input` returns a `string` (which is why `getlist[0]` is just the first character); you'll need to convert that to a list. – Scott Hunter May 22 '23 at 17:57
  • So you are saying you want to input the *name* of the list you want? – Scott Hunter May 22 '23 at 17:59
  • 1
    If you want the user to be able to enter `list1` and `list2`, it would be better to store your data in a dictionary with keys `"list1"` and `"list2"`: https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables – slothrop May 22 '23 at 17:59

1 Answers1

2

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])
John Gordon
  • 29,573
  • 7
  • 33
  • 58