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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

[0, 2, 9, 4, 8]

 
Approach #3 : Using json.loads()

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

[0, 2, 9, 4, 8]


My Personal Notes arrow_drop_up


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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.