Easiest way to convert string to list

Viewed 52

Let there be a string list_string = '[1,2,3]' the desired output would be the list inside the string, but not as a string bus as a list list_list = [1,2,3]

What is the easiest way to achieve this?

3 Answers

json module might be what you are looking for.

import json

list_string = '[1,2,3]'
list_list = json.loads(list_string)

print(list_list)  # [1, 2, 3]
print(list_list[0])  # 1

You can just call eval if you are very sure the string can be converted into list and does not contain dangerous code:

>> eval('[1,2,3]') == [1, 2, 3]
# True

One easy way would be to slice off the brackets and then use split:

>>> list_string = '[1,2,3]'
>>> list_list = list_string[1:-1].split(',')
>>> list_list
['1', '2', '3']
>>> list_list2 = [int(x) for x in list_string[1:-1].split(',')]
>>> list_list2
[1, 2, 3]
>>> list_list3 = list(map(int, list_string[1:-1].split(',')))
>>> list_list3
[1, 2, 3]
Related