Python | Convert string enclosed list to list (original) (raw)

Last Updated : 08 May, 2023

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) within the program. Here it takes the list enclosed within quotes as expression and runs it, and finally returns the list.

Python3

def convert(lst):

`` return eval (lst)

lst = "[0, 2, 9, 4, 8]"

print (convert(lst))

Time Complexity: O(n) where n is the length of the list
Auxiliary Space: O(1), constant extra space is required

Approach #2: Using literal_eval()

literal_eval() function works the same as eval() with the only difference that it raises an exception if the input isn’t a valid Python datatype, the code won’t be executed.

Python3

from ast import literal_eval

def convert(lst):

`` return literal_eval(lst)

lst = "[0, 2, 9, 4, 8]"

print (convert(lst))

Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(1) constant additional space is required

Approach #3 : Using json.loads()

Python3

from json import loads

def convert(lst):

`` return loads(lst)

lst = "[0, 2, 9, 4, 8]"

print (convert(lst))

The time complexity is O(n).

The auxiliary space is also O(n), where n is the length of the input string.

Approach #4 : Using replace(),split(),list(),map() methods

Python3

lst = "[0, 2, 9, 4, 8]"

lst = lst.replace( "[" , "")

lst = lst.replace( "]" , "")

x = lst.split( "," )

x = list ( map ( int , x))

print (x)

The time complexity is O(n), where n is the number of elements in the list.

The auxiliary space is also O(n)

Approach #5: Using regex

The approach using regex involves using the re (regular expression) module in Python. The re.findall(pattern, string) function returns a list of all matches of the pattern in the string.

In this case, the pattern being used is r”\d+”, which matches one or more digits. The r before the pattern string indicates a raw string, which helps to avoid any escape characters in the pattern string.

The convert() function then uses a list comprehension to iterate through the list of matches and convert each element to an integer. Finally, the list of integers is returned.

Note: Works only for integer array, if it is string array just modify the pattern

Python3

import re

def convert(lst):

`` return [ int (x) for x in re.findall(r "\d+" , lst)]

lst = "[0, 2, 9, 4, 8]"

print (convert(lst))

Time complexity: O(n) where n is the length of the list
Auxiliary Space: O(n)

Approach #6:Using list comprehension and strip() function:

Algorithm:

  1. Create a string variable lst and initialize it with the given string enclosed within square brackets.
  2. Slice the string from index 1 to -1 to remove the square brackets from both ends.
  3. Use the split() method to split the string into a list of substrings, using comma (‘,’) as the delimiter.
  4. Use a list comprehension to convert each substring into an integer, ignoring any leading or trailing whitespaces.
  5. Store the resulting list of integers in variable x.
  6. Print the value of x.

Python3

lst = "[0, 2, 9, 4, 8]"

x = [ int (i) for i in lst[ 1 : - 1 ].split( "," ) if i.strip()]

print (x)

Time complexity: O(n), where n is the length of the input string lst.

Auxiliary Space: O(n), where n is the length of the input string lst. This is because we create a new list of integers that has the same length as the input string.

Approach #7:Using itertools:

Algorithm:

Extract the string representation of the list from the input.
Split the string by comma separator, remove any leading or trailing whitespaces and convert each element to integer.
Create a list of lists, where each inner list contains a single integer element.
Flatten the list of lists into a single list using itertools.chain.from_iterable().
Print the final list.

Python3

import itertools

lst = "[0, 2, 9, 4, 8]"

x = list (itertools.chain.from_iterable([[ int (i)] for i in lst[ 1 : - 1 ].split( "," ) if i.strip()]))

print (x)

Time Complexity: O(n)

The algorithm has to go through each element in the input string list once to extract the integers and add them to the final list.
Space Complexity: O(n)

The algorithm creates a list of n lists, each containing a single integer element. The final flattened list also contains n integer elements. Therefore, the space complexity is O(n).