How to convert string representation of list to list in Python?

PythonServer Side ProgrammingProgramming

We can use ast.literal_eval() here to evaluate the string as a python expression. It safely evaluates an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None. 


fruits = "['apple', 'orange', 'banana']"
import ast
fruits = ast.literal_eval(fruits)
print fruits[1], fruits[0]


This will give us the output −

orange, apple
Published on 12-Dec-2017 11:16:29