Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: convert my_list = [ '[2,2]', '[0,3]' ] to my_list = [ [2,2], [0,3] ]

I have the following list:

my_list = [ '[2,2]', '[0,3]' ]

I want to convert it into

my_list = [ [2,2], [0,3] ]

Is there any easy way to do this in Python?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One way to avoid eval is to parse them as JSON:

import json


my_list = [ '[2,2]', '[0,3]' ]
new_list = [json.loads(item) for item in my_list]

This would not only avoid the possible negative risks of eval on data that you don’t control but also give you errors for content that is not valid lists.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading