Open In App

# Python | Convert list of string to list of list

Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let’s discuss certain ways in which this can be performed.

Method #1 : Using strip() + split()

A combination of strip and split functions can perform a particular task. The strip function can be used to get rid of the brackets and split function can make the data list comma-separated.

## Python3

 `# Python3 code to demonstrate``# to convert list of string to list of list``# using strip() + split()` `# initializing list``test_list ``=` `[``'[1, 4, 5]'``, ``'[4, 6, 8]'``]` `# printing original list``print` `(& quot``        ``The original ``list` `is` `: & quot``        ``+` `str``(test_list))` `# using strip() + split()``# to convert list of string to list of list``res ``=` `[i.strip(& quot``                ``[] & quot``                ``).split("``                       ``, & quot``                       ``) ``for` `i ``in` `test_list]` `# printing result``print` `(& quot``        ``The ``list` `after conversion ``is` `: & quot``        ``+` `str``(res))`

Output :

```The original list is : ['[1, 4, 5]', '[4, 6, 8]']
The list after conversion is : [['1', ' 4', ' 5'], ['4', ' 6', ' 8']]```

Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list

Method #2: Using list slicing and split()

The task performed in the above method can also be performed using the list slicing in which we slice all the elements from the second to the second last element hence omitting the last brackets.

## Python3

 `# Python3 code to demonstrate``# to convert the list of string to list of list``# using list slicing + split()` `# initializing list``test_list ``=` `[``'[1, 4, 5]'``, ``'[4, 6, 8]'``]` `# printing original list``print` `(& quot``        ``The original ``list` `is` `: & quot``        ``+` `str``(test_list))` `# using list slicing + split()``# to convert list of string to list of list``res ``=` `[i[``1``: ``-``1``].split(``', '``) ``for` `i ``in` `test_list]` `# printing result``print` `(& quot``        ``The ``list` `after conversion ``is` `: & quot``        ``+` `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#3: Using re.findall and list comprehension

This task can be performed using list comprehension for iterating over the list and re.findall function to make list with all elements that match the pattern.

## Python3

 `# Python3 code to demonstrate``# to convert list of string to list of list``# using list comprehension + re.findall``import` `re``# initializing list``test_list ``=` `[``'[1, 4, 5]'``, ``'[4, 6, 8]'``]` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))` `# using list comprehension + re.findall``# to convert list of string to list of list``res ``=` `[re.findall(``'[0-9]'``, i) ``for` `i ``in` `test_list]` `# printing 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#4: Using loop + eval() method

This task can be performed with the help of these functions. Loop is used to iterate over the list and eval is used to parse the expression present in the string.

## Python3

 `# Python3 code to demonstrate``# to convert list of string to list of list``# using loop + eval functions``import` `re``# initializing list``test_list ``=` `[``'[1, 4, 5]'``, ``'[4, 6, 8]'``]` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))` `# using loop + eval functions``# to convert list of string to list of list``for` `i ``in` `range``(``len``(test_list)):``    ``test_list[i] ``=` `eval``(test_list[i])` `# printing result``print``(``"The list after conversion is : "` `+` `str``(test_list))`

Output:

```The original list is : ['[1, 4, 5]', '[4, 6, 8]']
The list after conversion is : [[1, 4, 5], [4, 6, 8]]```

Method #5: Using list comprehension

## Python3

 `test_list ``=` `[``'[1, 4, 5]'``, ``'[4, 6, 8]'``]``x``=``[ ``eval``(i) ``for` `i ``in` `test_list ]``print``(x)`

Output

`[[1, 4, 5], [4, 6, 8]]`

Method #6: Using json

One possible approach to solving this problem is to use the json module. The json module allows you to parse JSON strings and convert them into Python objects, such as lists and dictionaries.

Here is an example of how you could use the json module to convert a list of strings to a list of lists:

## Python3

 `import` `json` `# Initialize the list of strings``string_list ``=` `[``'[1, 4, 5]'``, ``'[4, 6, 8]'``]` `# Convert the strings to lists using the json module``list_list ``=` `[json.loads(string) ``for` `string ``in` `string_list]` `print``(list_list)``#This code is contributed by Edula Vinay Kumar Reddy`

Output

`[[1, 4, 5], [4, 6, 8]]`

The time complexity of this approach is O(n), where n is the number of strings in the list. The space complexity is also O(n), as the result list will have the same number of elements as the input list.

Method #7: Using list comprehension and the ast.literal_eval() function from the ast module.

Algorithm:

1. Initialize a list test_list with some string elements.
2. Import the ast module, which provides a safe way to evaluate string literals as Python expressions.
3. Create a new list result.
4. Use a list comprehension to iterate through each string in test_list.
5. For each string, call ast.literal_eval(item) to safely evaluate the string as a Python expression.
6. Append the resulting list to result.
7. Print the result.

## Python3

 `import` `ast` `test_list ``=` `[``'[1, 4, 5]'``, ``'[4, 6, 8]'``]` `result ``=` `[ast.literal_eval(item) ``for` `item ``in` `test_list]` `print``(result)``#This code is contributed by tvsk`

Output

`[[1, 4, 5], [4, 6, 8]]`

Time Complexity:
The time complexity of this algorithm depends on the number of elements in the input list test_list. The list comprehension iterates through each element in the list, and for each element, ast.literal_eval() is called once. The time complexity of ast.literal_eval() is O(N), where N is the length of the input string. Therefore, the time complexity of the list comprehension is O(NM), where M is the number of elements in test_list. This makes the overall time complexity of the algorithm O(NM).

Auxiliary Space:
The space complexity of this algorithm is O(NM), where N is the maximum length of any element in test_list, and M is the number of elements in test_list. This is because the list comprehension creates a new list of lists that contains the converted values, which takes up O(NM) space. Additionally, the ast.literal_eval() function creates a temporary object to hold the result of the evaluation, which takes up O(N) space. However, since this temporary object is garbage collected after the function returns, it does not contribute to the overall space complexity of the algorithm.

Method #8: Using enumeration

• Initialize the list of strings test_list.
• Create an empty list x to store the result.
• Iterate over each element item and its index i in test_list using enumerate().
• Use the eval() function to evaluate the string item as a Python expression and convert it into a list.
• Append the resulting list to the x

## Python3

 `test_list ``=` `[``'[1, 4, 5]'``, ``'[4, 6, 8]'``]` `x ``=` `[]``for` `i, item ``in` `enumerate``(test_list):``    ``x.append(``eval``(item))` `print``(x)``#This code is contributed by Vinay pinjala.`

Output

`[[1, 4, 5], [4, 6, 8]]`

Time Complexity: O(n), where n is the length of the test_list. The eval() function has a constant time complexity and we are using a for loop to iterate over the list, which is also linear in time proportional to the length of the list.

Auxiliary Space: O(n * k), where n is the length of the test_list and k is the maximum length of any string in the list. This is because we are creating a new list for each string in the test_list, which takes additional space proportional to the length of the string. Since we are storing the resulting lists in the x list, which can have at most n elements, the total space complexity is n * k.