In this article we will see how to create a list of lists which contain string data types. The inner list themselves or of string data type and they may contain numeric or strings as their elements.
We use these two methods which will first separate out the lists and then convert each element of the list to a string.
list1 = [ '[0, 1, 2, 3]','["Mon", "Tue", "Wed", "Thu"]' ] print ("The given list is : \n" + str(list1)) print("\n") # using strip() + split() result = [k.strip("[]").split(", ") for k in list1] print ("Converting list of string to list of list : \n" + str(result))
Running the above code gives us the following result −
The given list is : ['[0, 1, 2, 3]', '["Mon", "Tue", "Wed", "Thu"]'] Converting list of string to list of list : [['0', '1', '2', '3'], ['"Mon"', '"Tue"', '"Wed"', '"Thu"']]
In this approach, we will use string slicing and then split the string to get the list of lists. Here the split function is applied along with a for loop.
list1 = [ '[0, 1, 2, 3]','["Mon", "Tue", "Wed", "Thu"]' ] print ("The given list is : \n" + str(list1)) print("\n") # using split() result = [i[1 : -1].split(', ') for i in list1] print ("Converting list of string to list of list : \n" + str(result))
Running the above code gives us the following result −
The given list is : ['[0, 1, 2, 3]', '["Mon", "Tue", "Wed", "Thu"]'] Converting list of string to list of list : [['0', '1', '2', '3'], ['"Mon"', '"Tue"', '"Wed"', '"Thu"']]