Naming Lists Using User Input
Solution 1:
The correct way to accomplish what you want here is a dict
of lists:
>>>lists = {}>>>lists['homework'] = [40, 60, 70]>>>lists['tests'] = [35, 99, 20]>>>lists
{'tests': [35, 99, 20], 'homework': [40, 60, 70]}
>>>
When you can ask for input, the input
function (raw_input
in Python 2.x) returns a string, which you can make the key of the dictionary.
Solution 2:
A direct answer to your question is that you can use vars()
to access your variable scope:
list_name = input("What would you like the name of the list to be?")
vars()[list_name] = []
Then if you enter "foo" at the prompt, you will have a variable named foo.
An indirect answer is that, as several other users have told you, you don't want to let the user choose your variable names, you want to be using a dictionary of lists, so that you have all the lists that users have created together in one place.
A program where variable names are chosen at runtime is a program that can never be bug-free. For instance, if the user types "input" into your prompt, you will redefine your input function, so that when that user or another tries to create another list, what you will get instead is an error:
>>> list_name = input("What would you like the name of the list to be?")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list'objectisnotcallable
Post a Comment for "Naming Lists Using User Input"