0

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?

  • 1
    Does 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 Answers2

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
  • 114
  • 7
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
  • 1,571
  • 3
  • 15
  • 32