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

Question:

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?

Asked By: AA10

||

Answers:

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

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

Answered By: jurez

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()
Answered By: I'mahdi

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.

Answered By: Hamatti
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.