pythonpandaslistdataframemore-itertools

How to convert a nested list of strings to a one list?


I wanted to convert a nested list of strings into a single list. For example, if there is a list like,

fruits = ['apple','orange, ['pineapple','grapes']]

I want to convert this to:

fruits = ['apple','orange','pineapple','grapes']

I tried using the more_itertools.chain.from_iterable(fruits) but the output I am getting is:

['a','p','p','l','e','o','r','a','n','g','e','pineapple','grapes']

Even tried [inner for item in fruits for inner in item], this also gves the same output as above.

I also tried [inner for item in fruits for inner in ast.literal_eval(item)] but this was giving an error ValueError: malformed string

Is there a workaround? Thanks in advance.


Solution

  • If you're using the more_itertools module try the collapse function:

    print(list(more_itertools.collapse(fruits)))
    

    Output:

    ['apple', 'orange', 'pineapple', 'grapes']