Convert list of string to list of list in Python


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 a string.

Example

 Live Demo

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 slice and spilt

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.

Example

 Live Demo

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

Updated on: 03-Mar-2020

656 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements