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 how to get rid of a nested list

Good evening,

I have a python variable like so

myList = ["['Ben'", " 'Dillon'", " 'Rawr'", " 'Mega'", " 'Tote'", " 'Case']"]

I would like it to look like this instead

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

myList = ['Ben', 'Dillon', 'Rawr', 'Mega', 'Tote', 'Case']

If I do something like this

','.join(myList)

It gives me what I want but the type is a String

I also would like it to keep the type of List. I have tried using the Join method and split method. And I have been debugging use the type() method. It tells me that the type in the original scenario is a list.

I appreciate any and all help on this.

>Solution :

Join the inner list elements, then call ast.literal_eval() to parse it as a list of strings.

import ast

myList = ast.literal_eval(",".join(myList))
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