Eval list of strings python

There isn't any need to import anything or to evaluate. You can do this in one line for most basic use cases, including the one given in the original question.

One liner

l_x = [i.strip() for i in x[1:-1].replace('"',"").split(',')]

Explanation

x = '[ "A","B","C" , " D"]'
# String indexing to eliminate the brackets.
# Replace, as split will otherwise retain the quotes in the returned list
# Split to convert to a list
l_x = x[1:-1].replace('"',"").split(',')

Outputs:

for i in range(0, len(l_x)):
    print(l_x[i])
# vvvv output vvvvv
'''
 A
B
C
  D
'''
print(type(l_x)) # out: class 'list'
print(len(l_x)) # out: 4

You can parse and clean up this list as needed using list comprehension.

l_x = [i.strip() for i in l_x] # list comprehension to clean up
for i in range(0, len(l_x)):
    print(l_x[i])
# vvvvv output vvvvv
'''
A
B
C
D
'''

Nested lists

If you have nested lists, it does get a bit more annoying. Without using regex (which would simplify the replace), and assuming you want to return a flattened list (and the zen of python says flat is better than nested):

x = '[ "A","B","C" , " D", ["E","F","G"]]'
l_x = x[1:-1].split(',')
l_x = [i
    .replace(']', '')
    .replace('[', '')
    .replace('"', '')
    .strip() for i in l_x
]
# returns ['A', 'B', 'C', 'D', 'E', 'F', 'G']

If you need to retain the nested list it gets a bit uglier, but it can still be done just with regular expressions and list comprehension:

import re

x = '[ "A","B","C" , " D", "["E","F","G"]","Z", "Y", "["H","I","J"]", "K", "L"]'
# Clean it up so the regular expression is simpler
x = x.replace('"', '').replace(' ', '')
# Look ahead for the bracketed text that signifies nested list
l_x = re.split(r',(?=\[[A-Za-z0-9\',]+\])|(?<=\]),', x[1:-1])
print(l_x)
# Flatten and split the non nested list items
l_x0 = [item for items in l_x for item in items.split(',') if not '[' in items]
# Convert the nested lists to lists
l_x1 = [
    i[1:-1].split(',') for i in l_x if '[' in i
]
# Add the two lists
l_x = l_x0 + l_x1

This last solution will work on any list stored as a string, nested or not.


We may sometime get data which contains strings but the structure of the data inside the stream is a Python list. In this article we will convert string enclosed list to an actual Python list which can be further used in data manipulation.

With eval

We know the eval function will give us the actual result which is supplied to it as parameter. So so we supplied the given string to the eval function and get back the Python list.

Example

 Live Demo

stringA = "['Mon', 2,'Tue', 4, 'Wed',3]"
# Given string
print("Given string : \n",stringA)
# Type check
print(type(stringA))
# using eval
res = eval(stringA)
# Result
print("The converted list : \n",res)
# Type check
print(type(res))

Output

Running the above code gives us the following result −

Given string :
['Mon', 2,'Tue', 4, 'Wed',3]

The converted list :
['Mon', 2, 'Tue', 4, 'Wed', 3]

With ast.literal_eval

In this approach, we take the estimate and use the literal_eval function by giving it the string as a parameter. It gives back the Python list.

Example

 Live Demo

import ast
stringA = "['Mon', 2,'Tue', 4, 'Wed',3]"
# Given string
print("Given string : \n",stringA)
# Type check
print(type(stringA))
# using literal_eval
res = ast.literal_eval(stringA)
# Result
print("The converted list : \n",res)
# Type check
print(type(res))

Output

Running the above code gives us the following result −

Given string :
['Mon', 2,'Tue', 4, 'Wed',3]

The converted list :
['Mon', 2, 'Tue', 4, 'Wed', 3]

With json.loads

The loads function injection module can do a similar conversion where the string is evaluated and actual Python list is generated.

Example

 Live Demo

import json
stringA = '["Mon", 2,"Tue", 4, "Wed",3]'
# Given string
print("Given string : \n",stringA)
# Type check
print(type(stringA))
# using loads
res = json.loads(stringA)
# Result
print("The converted list : \n",res)
# Type check
print(type(res))

Output

Running the above code gives us the following result −

Given string :
["Mon", 2,"Tue", 4, "Wed",3]

The converted list :
['Mon', 2, 'Tue', 4, 'Wed', 3]

Eval list of strings python

Updated on 04-Jun-2020 11:11:47

  • Related Questions & Answers
  • Python - Convert list of string to list of list
  • Convert list of string to list of list in Python
  • How to convert string representation of list to list in Python?
  • How to convert list to string in Python?
  • Convert list of numerical string to list of Integers in Python
  • Convert a string representation of list into list in Python
  • Convert a list to string in Python program
  • Python program to convert a list to string
  • Convert list of string into sorted list of integer in Python
  • Convert list of tuples to list of list in Python
  • Python - Convert List to custom overlapping nested list
  • Python - Convert given list into nested list
  • Convert list into list of lists in Python
  • Convert list of tuples into list in Python
  • Program to convert List of Integer to List of String in Java

How do you evaluate a string list in Python?

Convert String to List in Python Using the list() Function. The list() function converts the string into a list in Python. The list() function takes a string as an argument and converts it into a list. Every character in the string becomes the individual element in the list.

How do you evaluate a list in Python?

First, we define a string, that carries the syntax of a list. Next, we use eval to evaluate it. Finally, we can show that it has the properties of a Python list. Another example, where we allow the user to input the string to be evaluated.

How do you parse a string in Python?

Use str. Call str. split(sep) to parse the string str by the delimeter sep into a list of strings. Call str. split(sep, maxsplit) and state the maxsplit parameter to specify the maximum number of splits to perform.

What is the reliable method for transforming a string to a list?

The split() method is the recommended and most common method used to convert string to list in Python.