I have a list of strings and those strings are lists. Like this: [\'[1,2,3]\',\'[10,12,5]\']
, for example. I want to get a list of lists or even every list there: <
It is often not recommended, but you could use eval
for each string:
fun = ['[1,2,3]','[10,12,5]']
listy = [eval(x) for x in fun]
Outputs:
[[1, 2, 3], [10, 12, 5]]
This question provides excellent reason as to why using eval
can be a bad idea. I am just presenting it here as an option. eval
can pose a large security risk, as you are giving user input the full power of the Python interpreter. Additionally, it violates one of the fundamental principles of programming, which states that all of your executable code should directly map to your source code. Evaluating user input with eval
leads to executable code that evidently isn't in your source.
Using ast.literal_eval()
is preferable, and Padraic Cunningham's answer addresses how to use it effectively.