0

I am trying to convert a list enclosed in a quotes to a list. Is their any optimal way to do this.

Ex: list = "[1,2,3,4,5]"

Operation : Convert list which is string to a list

o/p: list = [1,2,3,4,5]
Jack Daniel
  • 2,091
  • 3
  • 26
  • 42
  • PS. http://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice – akash karothiya May 03 '17 at 06:29
  • Possible duplicate of [Convert string representation of list to list in Python](http://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list-in-python) – salmanwahed May 03 '17 at 06:29

6 Answers6

5

You can use ast.literal_eval() to safely evaluate the string:

Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

In [1]: from ast import literal_eval

In [2]: literal_eval("[1,2,3,4,5]")
Out[2]: [1, 2, 3, 4, 5]
alecxe
  • 414,977
  • 106
  • 935
  • 1,083
2

I'd, personally, use JSON for this as it would be the appropriate library for storing and retrieving lists and dictionaries:

import json
li = "[1,2,3,4,5]"
li = json.loads(li)
print(li)

Alternatively, you could use eval, but it's not recommended:

li = "[1,2,3,4,5]"
li = eval(li)
print(li)
Neil
  • 13,042
  • 2
  • 26
  • 48
2

eval is evil use ast.literal_eval:

>>> import ast
>>> ast.literal_eval("[1,2,3,4,5]")
[1, 2, 3, 4, 5]
Hackaholic
  • 15,927
  • 3
  • 44
  • 57
1

You can do

lst=eval("[1,2,3,4,5]")

Miriam Farber
  • 16,192
  • 11
  • 51
  • 69
0

Most direct:

li = eval("[1,2,3,4,5]")

list is a reserved keyword, don't use it as a variable name.

Only use eval if your string comes from a trusted source; if you call eval on a string like "import subprocess;subprocess.run('rm -rf /')", you're going to have problems.

Ken Wei
  • 2,605
  • 1
  • 7
  • 25
0

for me most simple way is: l=eval("[1,2,3]")

tso
  • 4,174
  • 2
  • 17
  • 30