Skip to content
Related Articles

Related Articles

Improve Article

Python | Convert list of string to list of list

  • Difficulty Level : Medium
  • Last Updated : 19 Jun, 2020

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. Let’s discuss certain ways in which this can be performed.

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




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

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.




# Python3 code to demonstrate 
# to convert the 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))

Output :

The original list is : ['[1, 4, 5]', '[4, 6, 8]']
The list after conversion is : [['1', ' 4', ' 5'], ['4', ' 6', ' 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. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :