0

I currently have a list of strings, the strings are a list but in a string (see below). I would like to make this a list of lists.

I currently have:

mylist = ['[1, 2]', '[2, 4, 9]', '[3]']

and I would like to end up with

mylist = [[1, 2], [2, 4, 9] [3]]

I have thought about using list() to make the elements a list, similar to the way int() makes a string into an integer. Also, split() isn't that useful to me as it just breaks everything down into one character strings and recreating the list from these could be messy.

Any quick way to do this which I might be missing?

  • 3
    What's `a`, `b`, `var`, `this` and `that`? – Lev Levitsky May 04 '14 at 17:39
  • Edited so that they are all numbers - in theory they could be anything, here just numbers would do. It's more of a question to ask if there is an easy way to get them out of the string. – user3601894 May 04 '14 at 17:44
  • Didn't see that article - thanks for the heads up. However, I got a malformed string error using that solution. Thankfully, the answer below solved my problem! – user3601894 May 04 '14 at 17:51

2 Answers2

1

ast.literal_eval is safer than eval:

import ast
mylist = [ast.literal_eval(str) for str in mylist]
user3286261
  • 391
  • 3
  • 7
0

You could use eval on your list:

myList = [eval(str) for str in myList]

Do watch out if your list contains user input though, since this could be used to execute unchecked code!

As user3286261 pointed out, you can use ast.literal_eval to avoid misuse of the standard eval.

mathsaey
  • 78
  • 1
  • 9