Change language

Python | Convert list of strings to list of list

|

Method # 1: Using strip () + split ()
The combination of strip and split function can accomplish a specific task. The strip function can be used to remove parentheses, and the split function can separate the list of data with commas.

# Python3 demo code
# to convert a list of strings to a list of list
# using strip () + split ()

 
# initializing list

test_list = [ ’[1, 4, 5]’ , ’[4, 6, 8]’ ]

 
# print original list

print ( "The origi nal list is: " + str (test_list))

 
# using strip () + split ()
# to convert a list of strings to a list of lists

res = [i.strip ( "[]" ). split ( "," ) for i in test_list]

 
# print 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 a split list and split ()
The task done in the above way can also be done using a slice of the list, in which we split all the elements from the second to the second last element, hence omitting the last parentheses.

# Python3 demo code
# to convert a list of strings to a list of list
# using list slicing + split ()

 
# initializing list

< code class = "plain"> test_list = [ ’[1, 4, 5] ’ , ’ [4, 6, 8] ’ ]

 
# print original list

print ( "The original list is:" + str (test_list))

 
# using the list splitting + split ()
# to transform the list lines to the list of list

res = [ i [ 1 : - 1 < code class = "plain">]. split ( ’,’ ) for i in test_list]

 
# print 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’]] 

Python | Convert list of strings to list of list Python functions: Questions

Python | Convert list of strings to list of list String Variables: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method