Python | Convert given list into nested list
Some times, we come over the data that is in string format in a list and it is required to convert it into a list of the list. This kind of problem of converting a list of strings to nested list is quite common in web development. Let’s discuss certain ways in which this can be performed.
Method #1: Using iteration
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
# Python code to convert list # of string into list of list # List initializationInput = ['Geeeks, Forgeeks', '65.7492, 62.5405', 'Geeks, 123', '555.7492, 152.5406'] temp = [] # Getting elem in list of list formatfor elem in Input: temp2 = elem.split(', ') temp.append((temp2)) # List initializationOutput = [] # Using Iteration to convert # element into list of listfor elem in temp: temp3 = [] for elem2 in elem: temp3.append(elem2) Output.append(temp3) # printingprint(Output) |
[[‘Geeeks’, ‘Forgeeks’], [‘65.7492’, ‘62.5405’], [‘Geeks’, ‘123’], [‘555.7492’, ‘152.5406’]]
Method #2 : Using ast [list with numeric values]
# Python code to convert list # of string into list of list # importingimport ast # List InitializationInput = ['12, 454', '15.72, 82.85', '52.236, 25256', '95.9492, 72.906'] # using ast to convertOutput = [list(ast.literal_eval(x)) for x in Input] # printingprint(Output) |
[[12, 454], [15.72, 82.85], [52.236, 25256], [95.9492, 72.906]]


