Home > Mobile >  Python: convert my_list = [ '[2,2]', '[0,3]' ] to my_list = [ [2,2], [0,3] ]
Python: convert my_list = [ '[2,2]', '[0,3]' ] to my_list = [ [2,2], [0,3] ]

Time:10-29

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?

CodePudding user response:

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.

CodePudding user response:

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:

  1. Why is using 'eval' a bad practice?
  2. Using python's eval() vs. ast.literal_eval()

CodePudding user response:

my_list = [eval(x) for x in my_list]

But beware: eval() is a potentially dangerous function, always validate its input.

  • Related