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 List to String List
- Python | Convert list of string to list of list
- Python | Convert a string representation of list into list
- Python | Convert list of string into sorted list of integer
- Python | Convert list of numerical string to list of Integers
- Python | Convert mixed data types tuple list to string list
- Python | Convert string List to Nested Character List
- Python Program to convert List of Integer to List of String
- Python - Convert String List to Key-Value List dictionary
- 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 | Convert String to tuple list
- Python program to convert a list to string
- Python | Convert heterogenous type String to List
- Python | Ways to convert list of ASCII value to string
- Python | Convert list of strings to space separated string
- Python | Convert string tuples to list tuples
- Python | Convert string list into multiple cases
- Python | Convert String to list of tuples
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.

