1

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?

KrokerOlaf
  • 23
  • 2

3 Answers3

1

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
Cubix48
  • 2,607
  • 2
  • 5
  • 17
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
YM Song
  • 103
  • 6
  • 1
    You could use [`ast.literal_eval`](https://docs.python.org/3/library/ast.html#ast.literal_eval) for a somewhat safer option. – Sash Sinha Mar 04 '22 at 17:14
1

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]
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40