Python | Convert list of string to list of list

Many times, we come over the dumped data that is found in the string format and we require it to be represented into the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to list to perform tasks is quite common in web development. Lets discuss certain ways in which this can be performed.

Method #1 : Using strip() + split()
Combination of strip and split function can perform the particular task. The strip function can be used to get rid of the brackets and split function can make the data list comma seperated.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# to convert list of string to list of list
# using strip() + split()
  
# initializing list  
test_list = [ '[1, 4, 5]', '[4, 6, 8]' ]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# using strip() + split()
# to convert list of string to list of list
res = [i.strip("[]").split(", ") for i in test_list]
  
# printing result 
print ("The list after conversion is : " +  str(res))

chevron_right


Output :

The original list is : ['[1, 4, 5]', '[4, 6, 8]']
The list after conversion is : [['1', ' 4', ' 5'], ['4', ' 6', ' 8']]

Method #2 : Using list slicing and split()
The task performed in the above method can also be performed using the list slicing in which we slice all the elements from second to second last element hence omitting the last brackets.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# to convert list of string to list of list
# using list slicing + split()
  
# initializing list  
test_list = [ '[1, 4, 5]', '[4, 6, 8]' ]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# using list slicing + split()
# to convert list of string to list of list
res = [i[1 : -1].split(', ') for i in test_list]
  
# printing result 
print ("The list after conversion is : " +  str(res))

chevron_right


Output :

The original list is : ['[1, 4, 5]', '[4, 6, 8]']
The list after conversion is : [['1', ' 4', ' 5'], ['4', ' 6', ' 8']]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.