1

So I have a list of python formatted like:

x = ['[1,2,3]', '[4,5,6,]', ...]

Is there a way to convert the "inner lists" to actual lists? So the output would be

x = [[1,2,3], [4,5,6], ....]

Thanks!

3 Answers 3

2

Another example with json:

>>> import json
>>> x = ['[1,2,3]', '[4,5,6]']
>>> [json.loads(y) for y in x]
[[1, 2, 3], [4, 5, 6]]

Please limit your strings to dicts and lists only.

Sign up to request clarification or add additional context in comments.

1 Comment

I accepted this answer versus the one proposed by khelwood (his solution did also solve my problem) because my full code already uses the json library.
1

You can use ast.literal_eval for this kind of conversion. You can use map to apply the conversion to each element of your list.

from ast import literal_eval

x = ['[1,2,3]', '[4,5,6,]']
x = map(literal_eval, x)
print x

gives

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

1 Comment

ast.literal_eval is great and it converts many types, but it'll give error if the list has any tags (i.e. <tag> etc)
1

You can use eval to evaluate strings as code.

x = ['[1,2,3]', '[4,5,6,]']
y = [eval(s) for s in x]

1 Comment

Use of eval is generally discouraged.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.