4

So I have a text file with a list saved in it, I know I could use some other object serialization for this, but I am just trying to do this with a text file cause why not. So I have a string variable, that has a list in it, but how do I turn the string back into a normal list. Here is my code

    #the normal list
    list1 = [1,2,3]

    #changing the list to a string so that it can be written to a text file
    str_list = str(list1)

So now what code do I need to change the list from a string to a normal list.

2 Answers2

3

You may use ast module with literal_eval function:

import ast
l = ast.literal_eval(s)

Or json module (warning! it works only for some subset of string representations, e.g. list of numbers - example given by you):

import json
l = json.loads(s)
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
2

You can use ast.literal_eval:

>>> s="[1,2,3]"
>>> from ast import literal_eval
>>> literal_eval(s)
[1, 2, 3]
Mazdak
  • 105,000
  • 18
  • 159
  • 188