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 31 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)]")
![](../../users/profiles/7161082.webp)
samusa
- 114
- 7
-
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)
![](../../users/profiles/4267439.webp)
rok
- 1,571
- 3
- 15
- 32