pythonarrayslist

convert a list which has single elements and lists into a flat list


How would you convert a list like this :

["foo",["banana","apple"], "banana", ["peaches","grapes"]]

into

["foo","banana","apple", "banana", "peaches",'grapes"]

I tried:

flat_list = [item for sublist in regular_list for item in sublist]

Solution

  • One approach using a nested list comprehension could be to check if each element is a list, and convert it to a list type otherwise:

    regular_list = ["foo",["banana","apple"], "banana", ["peaches","grapes"]]
    
    
    flat_list = [item for sublist in regular_list
                 for item in (sublist if isinstance(sublist, list) else [sublist])]
    
    print(flat_list)
    

    Result:

    ['foo', 'banana', 'apple', 'banana', 'peaches', 'grapes']