Last updated: Apr 9, 2024
Reading timeยท5 min
Use the ast.literal_eval()
method to convert the string representation of a
list to a list.
The ast.literal_eval()
method allows us to safely evaluate a string that
contains a Python literal.
from ast import literal_eval my_str = '[1,2,3,4]' # โ convert string representation of list to list (ast.literal_eval()) my_list = literal_eval(my_str) print(my_list) # ๐๏ธ [1, 2, 3, 4] print(type(my_list)) # ๐๏ธ <class 'list'>
The example uses the ast.literal_eval()
method to convert the string
representation of a list to an actual list object.
The ast.literal_eval() method allows us to safely evaluate a string that contains a Python literal.
Alternatively, you can use the str.strip()
method to remove the brackets.
This is a three-step process:
str.strip()
method to remove the brackets.my_str = '[1,2,3,4]' my_list = [int(item) for item in my_str.strip('[]').split(',')] print(my_list) # ๐๏ธ [1, 2, 3, 4]
The str.strip() method returns a copy of the string with the specified leading and trailing characters removed.
If you have a string containing quoted elements, use the str.replace()
method
to remove the unnecessary quotes.
my_str = '["a", "b", "c"]' my_list = my_str.strip('[]').replace('"', '').split(', ') print(my_list) # ๐๏ธ ['a', 'b', 'c']
str.replace()
method to remove the double quotes from the string before calling the str.split()
method.If you have a valid JSON string, you can also use the json.loads()
method to
convert the string representation of the list to a native Python list.
import json my_str = '["a", "b", "c"]' my_list = json.loads(my_str) print(my_list) # ๐๏ธ ['a', 'b', 'c'] print(type(my_list)) # ๐๏ธ <class 'list'>
The json.loads() method parses a JSON string into a native Python object.
This approach also works for arrays containing numbers.
import json my_str = '[1, 2, 3, 4]' my_list = json.loads(my_str) print(my_list) # ๐๏ธ [1, 2, 3, 4] print(type(my_list)) # ๐๏ธ <class 'list'>
If the data being parsed is not a valid JSON string, a JSONDecodeError
is
raised.
Note that this approach only works if you have a valid JSON string.
If there are nested strings wrapped in single quotes, this wouldn't work.
In that case, you should use the str.replace()
method to remove the
unnecessary quotes before splitting the string on each comma.
You can also use the re.findall()
method to convert the string representation
of a list to a list.
import re my_str = '[1, 2, 3, 4]' list_of_strings = re.findall(r'[0-9]+', my_str) print(list_of_strings) # ๐๏ธ ['1', '2', '3', '4'] list_of_integers = [int(item) for item in list_of_strings] print(list_of_integers) # ๐๏ธ [1, 2, 3, 4]
The same approach can be used if your list contains strings.
import re my_str = '["ab", "cd", "ef", "gh"]' list_of_strings = re.findall(r'\w+', my_str) print(list_of_strings) # ๐๏ธ ['ab', 'cd', 'ef', 'gh']
The re.findall method takes a pattern and a string as arguments and returns a list of strings containing all non-overlapping matches of the pattern in the string.
If your list contains numbers, use the following regular expression.
import re my_str = '[1, 2, 3, 4]' list_of_strings = re.findall(r'[0-9]+', my_str) print(list_of_strings) # ๐๏ธ ['1', '2', '3', '4']
The square brackets []
are called a character class and match the digits in
the specified range.
The plus +
causes the regular expression to match 1 or more repetitions of the
preceding character (the digits range).
The \w
character matches:
You can also use the eval()
function to convert the string representation of a
list to a list.
my_str = '[1, 2, 3, 4]' my_list = eval(my_str, {'__builtins__': None}, {}) print(my_list) # ๐๏ธ [1, 2, 3, 4] print(type(my_list)) # ๐๏ธ <class 'list'>
However, note that using eval
with user-supplied data isn't safe.
Instead, you should use the safer alternative - ast.literal_eval
.
from ast import literal_eval my_str = '[1,2,3,4]' my_list = literal_eval(my_str) print(my_list) # ๐๏ธ [1, 2, 3, 4] print(type(my_list)) # ๐๏ธ <class 'list'>
You can also use the map()
function to convert the string representation of a
list to a list.
my_str = '[1, 2, 3, 4]' my_list = list(map(int, my_str[1:-1].split(','))) print(my_list) # ๐๏ธ [1, 2, 3, 4]
If you have a list of strings, use the str.replace()
method instead of
map()
.
my_str = '["ab", "cd", "ef", "gh"]' my_list = list( map( lambda x: x.replace('"', ''), my_str[1:-1].split(',') ) ) print(my_list) # ๐๏ธ [1, 2, 3, 4]
We used string slicing to exclude the first and last characters from the string (the brackets) and split the string on each comma.
The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.
We passed the int() class to
the map()
function, so it gets called with each number from the list of
strings.
The last step is to convert the map object to a list.
You can also use the PyYAML module to convert the string representation of a list to a list.
First, make sure you have the PyYAML module installed by running the following command.
pip install PyYAML # ๐๏ธ or with pip3 pip3 install PyYAML
Now you can import and use the PyYAML module.
import yaml my_str = '[1, 2, 3, 4]' my_list = yaml.safe_load(my_str) print(my_list) # ๐๏ธ [1, 2, 3, 4]
The PyYAML module can also be used if your list contains strings.
import yaml my_str = '["ab", "cd", "ef", "gh"]' my_list = yaml.safe_load(my_str) print(my_list) # ๐๏ธ ['ab', 'cd', 'ef', 'gh']
The yaml.safe_load()
method loads a subset of the YAML language. This is
recommended for loading untrusted input.
There is also a yaml_full_load
method that you can use if you trust the data
that's being parsed.
import yaml my_str = '[1, 2, 3, 4]' my_list = yaml.full_load(my_str) print(my_list) # ๐๏ธ [1, 2, 3, 4]
yaml.full_load()
method takes a YAML document, parses it and produces the corresponding Python object.Note that using the full_load()
method with untrusted input is not
recommended.
If you work with untrusted data, use the yaml.safe_load()
method instead.
You can learn more about the related topics by checking out the following tutorials: