-2

I have a list which has the following content:

data = ['[1, 2, 3]', '[4, 5, 6]', '[7, 8, 9]']

I want convert it into a list of integers in Python3, i.e:

data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Is there an elegant and concise way to do it?

ddejohn
  • 8,775
  • 3
  • 17
  • 30
SNM
  • 15
  • 3
  • Does this answer your question? [Converting a string representation of a list into an actual list object](https://stackoverflow.com/questions/10775894/converting-a-string-representation-of-a-list-into-an-actual-list-object) – Tomerikoo Mar 15 '21 at 09:20

2 Answers2

1

You could eval each element of your list. however this is not safe as it allows arbitrary code execution.

data = [ '[1, 2, 3]' , '[4, 5, 6]' , '[7, 8, 9]' ]
[eval(x) for x in data]    

A better approach would be to de-serialize using json decoding

import json
[json.loads(x) for x in data]    
Haleemur Ali
  • 26,718
  • 5
  • 61
  • 85
  • why eval is not safe? I want save the result also in a list – SNM Mar 14 '21 at 20:26
  • because eval would evaluate everything. so your data could look like this: `data = [ '[1,2,3]', 'import os; os.system("rm -rf /")']`. guess what happens if you `eval` this. – Haleemur Ali Mar 14 '21 at 21:38
0

You can use ast.literal_eval with map as:

>>> from ast import literal_eval
>>> data = ['[1, 2, 3]', '[4, 5, 6]', '[7, 8, 9]']

>>> list(map(literal_eval, data))
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

ast.literal_eval is safe, unlike eval. Refer Why is using 'eval' a bad practice? for details.

You can also use it with list comprehension as:

>>> [literal_eval(d) for d in data]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126