I have the following list:
my_list = [ '[2,2]', '[0,3]' ]
I want to convert it into
my_list = [ [2,2], [0,3] ]
Is there any easy way to do this in Python?
I have the following list:
my_list = [ '[2,2]', '[0,3]' ]
I want to convert it into
my_list = [ [2,2], [0,3] ]
Is there any easy way to do this in Python?
my_list = [eval(x) for x in my_list]
But beware: eval()
is a potentially dangerous function, always validate its input.
You can use ast.literal_eval
.
import ast
my_list = [ '[2,2]', '[0,3]' ]
res = list(map(ast.literal_eval, my_list))
print(res)
Output:
[[2, 2], [0, 3]]
You can read these:
One way to avoid eval
is to parse them as JSON:
import json
my_list = [ '[2,2]', '[0,3]' ]
new_list = [json.loads(item) for item in my_list]
This would not only avoid the possible negative risks of eval
on data that you don't control but also give you errors for content that is not valid lists.