Convert string representation of list to Python list

How to convert string representation of python list to list python
Note
This tutorial is written for Python 3, but it also works for Python 2

Assume you have a string representation of list like this:

s = '["hello", "world", 1, 2, 3]'

And you to convert s string to Python list like this:

s_list = ["hello", "world", 1, 2, 3]

There are some solutions to do that.

Using literal_eval function from ast module.

>>> import ast
>>> s = '["hello", "world", 1, 2, 3]'
>>> s_list = ast.literal_eval(s)
>>> s
["hello", "world", 1, 2, 3]

ast.literal_eval(node_or_string) safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None. That means you can also use ast.literal_eval() to convert a string representation of tuple, dict, set to Python tuple, dict, set

Using json module

You can also use json module to achieve the same result. json module a is a better solution whenever there is a stringified list of dictionaries. The json.loads(s) function can be used to convert it to a list.

>>> import json
>>> s = '["hello","world","1", "2", "3"]'
>>> json.loads(s)
["hello","world","1", "2", "3"]

Similarly

>>> s = '[ "hello","world","1", "2", "3", {"id": "45"}]'
>>> json.loads(s)
["hello","world","1", "2", "3", {"id": "45"}]
Last modified October 4, 2020