Python how to get rid of a nested list

Question:

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

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.

Asked By: Taner

||

Answers:

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))
Answered By: Barmar

Also can be done by truncating Strings, therefore avoiding the import of ast.

myList[5] = (myList[5])[:-1]
for n in range(0, len(myList)):
    myList[n] = (myList[n])[2:-1]
Answered By: Kineye
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.