2

I just started playing around with python. I know that we can convert any list to a string using str() Like:

>>> l = [[1,1] , [2,2] , [3,3]]
>>> l
[[1, 1], [2, 2], [3, 3]]
>>> type(l)
<type 'list'>
>>> str(l)
'[[1, 1], [2, 2], [3, 3]]'
>>> list_string = str(l)
>>> list_string
'[[1, 1], [2, 2], [3, 3]]'
>>> type(list_string)
<type 'str'>

Is there a way to convert list_string back to a 2d list ?? Basically, is there a function to convert this back to its original form ?

old_list = magic_conversion_func(list_string)

>>>old_list
[[1, 1], [2, 2], [3, 3]]

I tried list() but that converts every char in the string to a new list element.

>>> list(list_string)
['[', '[', '1', ',', ' ', '1', ']', ',', ' ', '[', '2', ',', ' ', '2', ']', ',', ' ', '[', '3', ',', ' ', '3', ']', ']']

that is not what I want

tomkaith13
  • 1,717
  • 4
  • 27
  • 39

2 Answers2

4

Use ast.literal_eval

>>> list_string = '[[1, 1], [2, 2], [3, 3]]'
>>> import ast
>>> type(ast.literal_eval(list_string))
<type 'list'>
Puffin GDI
  • 1,702
  • 5
  • 27
  • 37
1

using eval

>>> l = [[1,1] , [2,2] , [3,3]]
>>> list_string = str(l)
>>> eval(list_string)
[[1, 1], [2, 2], [3, 3]]

but eval should be used with caution, right? a thread on eval safety.

This works as well, close to what you tried with list:

import numpy as np
print np.array(list_string)
Community
  • 1
  • 1
kiriloff
  • 25,609
  • 37
  • 148
  • 229