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
  • 44,601
  • 17
  • 110
  • 191
Niko Gamulin
  • 63,517
  • 91
  • 213
  • 274

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
  • 314,667
  • 49
  • 610
  • 551
  • 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,277
  • 18
  • 25