Skip to content
Related Articles

Related Articles

Python | Convert string enclosed list to list

View Discussion
Improve Article
Save Article
  • Last Updated : 20 May, 2019

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))

Output:

[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))

Output:

[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))

Output:

[0, 2, 9, 4, 8]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!