Skip to content
Related Articles

Related Articles

Python | Convert string enclosed list to list
  • 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.

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]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :