I have array a="[(1,2),(2,3),(3,4)]".How can I convert this array to normal list format in Python like a=[(1,2),(2,3),(3,4)] where I can directly access elements using an index?
Asked
Active
Viewed 80 times
0
-
1Does this answer your question? [How to convert string representation of list to a list?](https://stackoverflow.com/questions/1894269/how-to-convert-string-representation-of-list-to-a-list) – rok May 10 '21 at 11:03
2 Answers
1
Use ast
as the other answer recommends. Why?
Be caution with useing eval
. You can open doors for vunerabilities.
eval("[(1,2),(2,3),(3,4)]")
# [(1, 2), (2, 3), (3, 4)]
Update: ast
gives you errors if the input isn't a valid Python.
import ast
ast.literal_eval("[(1,2),(2,3),(3,4)]")

samusa
- 449
- 2
- 11
-
1[`eval is eval`](https://stackoverflow.com/a/1832957/4985099) avoid it !! – sushanth May 10 '21 at 11:00
1
You can use ast, which is safer than eval.
import ast
a="[(1,2),(2,3),(3,4)]"
x = ast.literal_eval(a)

rok
- 2,574
- 3
- 23
- 44