0

I want to use input() to call one of three possible lists (a, b, or c) and then run functions on that chosen list.

At one point I had this working, so not sure what I changed. I think it's an issue with the way it's declared.

a = ["1","2","3"]
b = ["4","5","6"]
c = ["7","8","9"]

choice = input("Choose a, b, or c")

print choice[0]

some_function(choice)

If input is a I want to get "1" as the output.

2 Answers 2

2

Put your lists in a dict instead of 3 separate variables.

choices = {
    'a': ["1","2","3"],
    'b': ["4","5","6"],
    'c': ["7","8","9"],
}

choice = input("Choose a, b, or c")

print(choices[choice])
Sign up to request clarification or add additional context in comments.

4 Comments

choices.get(choice, None) would prevent exceptions for an invalid input (though its arguable wether exceptions should be ignored here or not)
Yeah, I deliberately avoided the issue of bad input here.
I figured but I leave that option as a comment just in case a future reading uses it :)
Thanks, that did it.
0

Just use a dictionary. Here is how that would work.

dictionary = {"a": ["1", "2", "3"]} choice = input("Choose a, b, or c: ")

print(dictionary[choice][0])

Dictionary uses a key and value. Your key here would be the string "a" (Keys are immutable) and value would be the corresponding array. Dictionary[key] gives you a value and Dictionary[key][0] is basically value[0]. So you are simply indexing the list.

You can use one dictionary for all declared lists.

dictionary = {"a": ["1", "2", "3"], "b": ["5", "6", "7"]} and onwards....

Plus they are more efficient than lists.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.