0

I want to ask the user which list they would like to access, then retrieve that list. I dont really have any code for this, because I'm currently just brainstorming. I couldn't really find a proper answer so here is a sample code I just made for the sake of explaining what I'm trying to do:

list1=[1, 2, 3, 4, 5]
list2=[6, 7, 8, 9, 10]
list3=['s', 'r', 't', 'd']

user_input=input('which list do you want to access')

I know that I can use if and elseif statements but the code I plan on making will have a large number of lists and I want a more efficient way to achieve this.

5
  • what do you mean by "retrieving a list" ? printing it ? Commented May 28, 2022 at 10:04
  • You could place the lists in a dictionary, as key, list pairs. This way a person identifies which list they want by the key (which could be 0, 1, 2, etc.) which then maps to the desired list in the dictionary. Commented May 28, 2022 at 10:06
  • Do mylist={ } then mylist["1"] = [1, 2, 3, 4, 5] etc. Then ask the user for a number in the range 1..3 and get the desired list like this: mylist[user_input]. Commented May 28, 2022 at 10:09
  • @azro i want to access it and use it for further purposes which could be printing yes Commented May 28, 2022 at 10:10
  • Does this answer your question? How do I create variable variables? Commented May 28, 2022 at 10:12

2 Answers 2

1

You can use dictionary to map input string to the right list

list1=[1, 2, 3, 4, 5]
list2=[6, 7, 8, 9, 10]
list3=['s', 'r', 't', 'd']

lists = {
    'list1': list1,
    'list2': list2,
    'list3': list3
}

user_input=input('which list do you want to access: ')
if user_input in lists:
    print('selected list:', lists[user_input])
else:
    print('no list matched')

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

Comments

1

You can either use a nested list and access the lists by their index, or as already mentioned by @tax evader, use a dictionary to map the name of the list to the list itself:

# Using a list
def retrieve_list() -> list:
    lists = [
        [1, 2, 3, 4, 5]
        [6, 7, 8, 9, 10],
        ['s', 'r', 't', 'd']
    ]
    
    user_input = input("Which list do you want to access? ")
    try:
        return lists[int(user_input)-1]
    except:
        return None

# Using a dictionary
def retrieve_list() -> list:
    lists = {
        "1": [1, 2, 3, 4, 5]
        "2": [6, 7, 8, 9, 10],
        "3": ['s', 'r', 't', 'd']
    }
    
    user_input = input("Which list do you want to access? ")
    return lists.get(user_input, None)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.