Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Convert List of String List to String List
Next article icon

Python | Convert string enclosed list to list

Last Updated : 08 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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




# Python3 program to ways to convert
# list enclosed within string to list
 
 
def convert(lst):
    return eval(lst)
 
 
# Driver code
lst = "[0, 2, 9, 4, 8]"
print(convert(lst))
 
 
Output:
[0, 2, 9, 4, 8]

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




# Python3 program to ways to convert
# list enclosed within string to list
from ast import literal_eval
 
 
def convert(lst):
    return literal_eval(lst)
 
 
# Driver code
lst = "[0, 2, 9, 4, 8]"
print(convert(lst))
 
 
Output:
[0, 2, 9, 4, 8]

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




# Python3 program to ways to convert
# list enclosed within string to list
from json import loads
 
 
def convert(lst):
    return loads(lst)
 
 
# Driver code
lst = "[0, 2, 9, 4, 8]"
print(convert(lst))
 
 
Output:
[0, 2, 9, 4, 8]

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




# Python3 program to ways to convert
# list enclosed within string to list
 
lst = "[0, 2, 9, 4, 8]"
lst = lst.replace("[", "")
lst = lst.replace("]", "")
x = lst.split(",")
x = list(map(int, x))
print(x)
 
 
Output
[0, 2, 9, 4, 8]

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




# Python3 program to ways to convert
# list enclosed within string to list
import re
 
def convert(lst):
    return [int(x) for x in re.findall(r"\d+", lst)]
# Driver code
lst = "[0, 2, 9, 4, 8]"
print(convert(lst))
#This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
[0, 2, 9, 4, 8]

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)
#This code is contributed by tvsk
 
 
Output
[0, 2, 9, 4, 8]

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)
#This code is contributed by Jyothi pinjala.
 
 
Output
[0, 2, 9, 4, 8]

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).



Next Article
Python | Convert List of String List to String List

S

Smitha Dinesh Semwal
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python | Convert List of lists to list of Strings
    Interconversion of data is very popular nowadays and has many applications. In this scenario, we can have a problem in which we need to convert a list of lists, i.e matrix into list of strings. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + joi
    4 min read
  • 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() + isd
    6 min read
  • Convert String Float to Float List in Python
    We are given a string float we need to convert that to float of list. For example, s = '1.23 4.56 7.89' we are given a list a we need to convert this to float list so that resultant output should be [1.23, 4.56, 7.89]. Using split() and map()By using split() on a string containing float numbers, we
    3 min read
  • Convert Dictionary to String List in Python
    The task of converting a dictionary to a string list in Python involves transforming the key-value pairs of the dictionary into a formatted string and storing those strings in a list. For example, consider a dictionary d = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}. Converting this to a st
    3 min read
  • Python - Convert List of Integers to a List of Strings
    We are given a list of integers and our task is to convert each integer into its string representation. For example, if we have a list like [1, 2, 3] then the output should be ['1', '2', '3']. In Python, there are multiple ways to do this efficiently, some of them are: using functions like map(), re
    3 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
    8 min read
  • Convert list of strings to list of tuples in Python
    Sometimes we deal with different types of data types and we require to inter-convert from one data type to another hence interconversion is always a useful tool to have knowledge. This article deals with the converse case. Let's discuss certain ways in which this can be done in Python. Method 1: Con
    5 min read
  • Python - Convert String to List of dictionaries
    Given List of dictionaries in String format, Convert into actual List of Dictionaries. Input : test_str = ["[{'Gfg' : 3, 'Best' : 8}, {'Gfg' : 4, 'Best' : 8}]"] Output : [[{'Gfg': 3, 'Best': 8}, {'Gfg': 4, 'Best': 8}]] Explanation : String converted to list of dictionaries. Input : test_str = ["[{'G
    4 min read
  • Convert Float String List to Float Values-Python
    The task of converting a list of float strings to float values in Python involves changing the elements of the list, which are originally represented as strings, into their corresponding float data type. For example, given a list a = ['87.6', '454.6', '9.34', '23', '12.3'], the goal is to convert ea
    3 min read
  • Python - List of float to string conversion
    When working with lists of floats in Python, we may often need to convert the elements of the list from float to string format. For example, if we have a list of floating-point numbers like [1.23, 4.56, 7.89], converting them to strings allows us to perform string-specific operations or output them
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences