Home > OS >  Python how to get rid of a nested list
Python how to get rid of a nested list

Time:08-25

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.

CodePudding user response:

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))

CodePudding user response:

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]
  • Related