1

I have the tuple inside the list and I want to convert all the elements into 2d list. The tuple inside the list is like this

 myList=[("[['MDLSBRO', 'TABY'], ['TABY', 'YAAM'], ['YAAM', 'NLRTN'], ['NLRTN', 'THIRSK'], ['THIRSK', 'YORK']]",)]

I have no clue how to break this stuff but I want to convert like this any help would be appreciated.

 myList=[['MDLSBRO', 'TABY'], ['TABY', 'YAAM'], ['YAAM', 'NLRTN'], ['NLRTN', 'THIRSK'], ['THIRSK', 'YORK']]
Tayyab Vohra
  • 1,512
  • 3
  • 22
  • 49

1 Answers1

3

Try ast.literal_eval

>>> import ast
>>> myList=[("[['MDLSBRO', 'TABY'], ['TABY', 'YAAM'], ['YAAM', 'NLRTN'], ['NLRTN', 'THIRSK'], ['THIRSK', 'YORK']]",)]
>>> myList = ast.literal_eval(myList[0][0])
>>> myList
[['MDLSBRO', 'TABY'], ['TABY', 'YAAM'], ['YAAM', 'NLRTN'], ['NLRTN', 'THIRSK'], ['THIRSK', 'YORK']]

See this for why you should use this over eval.

Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
  • what is the advantage of `ast.literal_eval` over builtin `eval`? it worked fine for me – luigigi Feb 18 '20 at 12:35
  • `eval` tries to implement anything that is inside the string that is passed, this can be especially problematic if you have untrusted code, on the other hand, `ast.literal_eval` will only evaluate if the element inside the string is a valid python data structure. – Sayandip Dutta Feb 18 '20 at 12:36