Python | Convert string enclosed list to list
Given a list enclosed within string (or quotes), write a Python program to convert the given string to list type.
Examples:
Input : "[0, 2, 9, 4, 8]" Output : [0, 2, 9, 4, 8] Input : "['x', 'y', 'z']" Output : ['x', 'y', 'z']
Approach #1 : Python eval()
The eval() method parses the expression passed to this method and runs python expression (code) within the program. Here it takes the list enclosed within quotes as expression and runs it, and finally returns the list.
# Python3 program to ways to convert # list enclosed within string to list def convert(lst): return eval(lst) # Driver code lst = "[0, 2, 9, 4, 8]"print(convert(lst)) |
[0, 2, 9, 4, 8]
Approach #2 : Using literal_eval()
literal_eval() function works same as eval() with the only difference that it raises an exception if the input isn’t a valid Python datatype, the code won’t be executed.
# Python3 program to ways to convert # list enclosed within string to list from ast import literal_eval def convert(lst): return literal_eval(lst) # Driver code lst = "[0, 2, 9, 4, 8]"print(convert(lst)) |
[0, 2, 9, 4, 8]
Approach #3 : Using json.loads()
# Python3 program to ways to convert # list enclosed within string to list from json import loads def convert(lst): return loads(lst) # Driver code lst = "[0, 2, 9, 4, 8]"print(convert(lst)) |
[0, 2, 9, 4, 8]
Recommended Posts:
- Python | Convert list of string to list of list
- Python | Convert list of string into sorted list of integer
- Python | Convert list of numerical string to list of Integers
- Python | Convert a string representation of list into list
- Python | Convert list of tuples to list of list
- Python | Program to convert String to a List
- Python | Convert a list of characters into a string
- Python program to convert a list to string
- Python | Ways to convert list of ASCII value to string
- Python | Convert list of strings to space separated string
- Python | Convert a nested list into a flat list
- Python | Convert list of tuples to list of strings
- Python | Convert list of strings to list of tuples
- Python | Convert 1D list to 2D list of variable length
- Python | Convert list into list of lists
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



