Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python, let user define list variable

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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'>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading