Computer >> Computer tutorials >  >> Programming >> Python

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


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. 

example

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

Output

This will give us the output −

orange, apple