1

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'mahdi
  • 23,382
  • 5
  • 22
  • 30
AA10
  • 207
  • 1
  • 7

3 Answers3

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

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

jurez
  • 4,436
  • 2
  • 12
  • 20
1

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()
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
1

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.

Hamatti
  • 1,210
  • 10
  • 11