1

I am trying to convert a string to list and as a newbie don't know what's the easiest way to do that.

Having the list, for example:

strList = "[[1,2,3],[4,5,6]]"

is there any python function that simply splits the string above? I tried to use the method .split() but it returns

>>> list("[[1,2,3],[4,5,6]]".split())
['[[1,2,3],[4,5,6]]']

What I would like to get is

result = [[1,2,3],[4,5,6]]

so the result[0] would return [1,2,3] and result[0][1] would return 2

Marcin
  • 46,667
  • 17
  • 117
  • 197
Niko Gamulin
  • 64,879
  • 93
  • 219
  • 275

2 Answers2

10

Use ast.literal_eval:

>>> import ast
>>> ast.literal_eval("[[1,2,3],[4,5,6]]")
[[1, 2, 3], [4, 5, 6]]
>>> result = _
>>> result[0]
[1, 2, 3]
>>> result[0][1]
2
falsetru
  • 336,967
  • 57
  • 673
  • 597
  • As a side note, `ast.literal_eval` only recognize a subset of Python syntax. It has however an evil built-in twin: [eval](http://docs.python.org/2/library/functions.html#eval). In this case, the first is way better. – Cyrille Sep 16 '13 at 12:19
3

Another way would be to use json

import json
result = json.loads('[[1,2,3],[4,5,6]]')
TobiMarg
  • 3,487
  • 19
  • 25