0
I have List in string type ... Can i convert to list type?
a='[[2,3],[4,5]]' (class string) to a=[[2,3],[4,5]] (class list)
1 Answer
+ 2
It's best if you include a language when you ask a question. I'm going to assume that you mean Python since that is what it looks like from what you're learning here on SL.
You can create a list from the characters of a string in Python by simply passing the string into the list() function and saving its result into a variable.
This, however, will give you the result:
['[', '[', '2', ',', '3', ']', ',', '[', '4', ',', '5', ']', ']']
Which is not what you're looking for.
So what you want to do is evaluate the string list representation into an actual list.
You can use the function eval() for this. Note, this may be deemed unsafe.
a = '[[2,3],[4,5]]'
a = eval(a)
I would suggest that instead you use literal_eval() from the ast package.
import ast
a = '[[2,3],[4,5]]'
a = ast.literal_eval(a)
# yes this does work in the playground