Open In App

Python | Convert list of string to list of list

Last Updated : 18 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.



Similar Reads

Python | Convert List of String List to String List
Sometimes while working in Python, we can have problems of the interconversion of data. This article talks about the conversion of list of List Strings to joined string list. Let's discuss certain ways in which this task can be performed. Method #1 : Using map() + generator expression + join() + isdigit() This task can be performed using a combinat
6 min read
Convert Unicode String to a Byte String in Python
Python is a versatile programming language known for its simplicity and readability. Unicode support is a crucial aspect of Python, allowing developers to handle characters from various scripts and languages. However, there are instances where you might need to convert a Unicode string to a regular string. In this article, we will explore five diff
2 min read
Python | Convert a string representation of list into list
Many times, we come across 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 a list in Python to perform tasks is quite common in web development. Convert a string of a list in
6 min read
Python | Convert list of string into sorted list of integer
Given a list of string, write a Python program to convert it into sorted list of integer. Examples: Input: ['21', '1', '131', '12', '15'] Output: [1, 12, 15, 21, 131] Input: ['11', '1', '58', '15', '0'] Output: [0, 1, 11, 15, 58] Let's discuss different methods we can achieve this task. Method #1: Using map and sorted() C/C++ Code # Python code to
4 min read
Python | Convert list of numerical string to list of Integers
Many times, the data we handle might not be in the desired form for any application and has to go through the stage of preprocessing. One such kind of form can be a number in the form of a string that too is a list in the list and we need to segregate it into digit-separated integers. Let's discuss certain ways in Python in which this problem can b
6 min read
Python | Convert string enclosed list to list
Given a list enclosed within a string (or quotes), write a Python program to convert the given string to list type. Examples: Input : "[0, 2, 9, 4, 8]" Output : [0, 2, 9, 4, 8] Input : "['x', 'y', 'z']" Output : ['x', 'y', 'z'] Approach #1: Python eval() The eval() method parses the expression passed to this method and runs python expression (code)
5 min read
Python | Convert mixed data types tuple list to string list
Sometimes, while working with records, we can have a problem in which we need to perform type conversion of all records into a specific format to string. This kind of problem can occur in many domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + tuple() + str() + generator expression The co
5 min read
Python | Convert string List to Nested Character List
Sometimes, while working with Python, we can have a problem in which we need to perform interconversion of data. In this article we discuss converting String list to Nested Character list split by comma. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split() The combination of above functional
7 min read
Python - Convert String List to Key-Value List dictionary
Given a string, convert it to key-value list dictionary, with key as 1st word and rest words as value list. Input : test_list = ["gfg is best for geeks", "CS is best subject"] Output : {'gfg': ['is', 'best', 'for', 'geeks'], 'CS': ['is', 'best', 'subject']} Explanation : 1st elements are paired with respective rest of words as list. Input : test_li
8 min read
Python Program to convert List of Integer to List of String
Given a List of Integers. The task is to convert them to a List of Strings. Examples: Input: [1, 12, 15, 21, 131]Output: ['1', '12', '15', '21', '131']Input: [0, 1, 11, 15, 58]Output: ['0', '1', '11', '15', '58']Method 1: Using map() [GFGTABS] Python3 # Python code to convert list of # string into sorted list of integer # List initialization list_i
5 min read
Practice Tags :
three90RightbarBannerImg