Python, let user define list variable
Question:
Trying to enable a user to input a mixed list in the correct format, ie with square brackets and commas already separating values.
Using the input() function saves the entire input as a string.
Using list() around this, just makes every character of the string a separate part of the list.
I see for loops can be used and so can split function, but that won’t work with the kind of list I’m trying to input. I need the user to be able to define the list themselves. Is this even possible?
Essentially, user should be able to input e.g.
["d",3,18,"{ds}"]
and then my script runs the function using their defined list.
Am I just missing something or is there not a way to do this?
Answers:
IIUC, you’re looking for ast.literal_eval
:
from ast import literal_eval
pre_L = input("Enter a list, please: ")
L = literal_eval(pre_L)
Output :
print(L, type(L))
Enter a list, please: ["d",3,18,"{ds}"]
['d', 3, 18, '{ds}'] <class 'list'>
Trying to enable a user to input a mixed list in the correct format, ie with square brackets and commas already separating values.
Using the input() function saves the entire input as a string.
Using list() around this, just makes every character of the string a separate part of the list.
I see for loops can be used and so can split function, but that won’t work with the kind of list I’m trying to input. I need the user to be able to define the list themselves. Is this even possible?
Essentially, user should be able to input e.g.
["d",3,18,"{ds}"]
and then my script runs the function using their defined list.
Am I just missing something or is there not a way to do this?
IIUC, you’re looking for ast.literal_eval
:
from ast import literal_eval
pre_L = input("Enter a list, please: ")
L = literal_eval(pre_L)
Output :
print(L, type(L))
Enter a list, please: ["d",3,18,"{ds}"]
['d', 3, 18, '{ds}'] <class 'list'>