Entering a list as an user-input in Python

You probably know and use the input() command in Python for interactive data entry. Sometimes, you wish to enter a list. If you use the input() command, it will store the list as a string. Below i will show you how to convert that string to a list using json.

>>> ls=input(‘enter a list’)
enter a list [1,2,3]
>>> ls
‘ [1,2,3]’
>>> type(ls)
<class ‘str’>
>>> import json
>>> str_list=input(‘enter a list’)
enter a list[1,2,3]
>>> str_list
‘[1,2,3]’
>>> my_list=json.loads(str_list)
>>> my_list
[1, 2, 3]
>>> type(my_list)
<class ‘list’>

Leave a Comment

Your email address will not be published. Required fields are marked *