Computer >> Computer tutorials >  >> Programming >> Python

Python - Convert list of string to list of list


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.

Using strip and split

We use these two methods which will first separate out the lists and then convert each element of the list to astring.

Example

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

Output

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"']]

Using split and slicing

We can also achieve the above result by using only the split method and string slicing. The list them selves gets sliced to get each element and then each element gets converted to a string.

Example

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

Output

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"']]