List of Lists of Lists of... to one List

Viewed 52

How can I convert List of Lists of Lists into one List? For example I would like to make one list which contains all elements from all nested lists, i.e if I have:

l = [[["A", ["B"]], ["C", "D"]], [["E", "F"], ["A"]]]

then the results should be:

["A", "B", "C", "D", "E", "F", "A"]
1 Answers

This is perhaps not the most efficient, or most pythonic way:

def extract(a):
    #recursive algorithm for extracting items from a list of lists and items
    if type(a) is list:
        l = []
        for item in a:
            l+=extract(item)
        return l
    else:
        return [a]

Essentially what this does is check if the input is a list. If it is, we split it up into its elements, and run the function on those elements. When we get to a non-list, we return those, forming a complete list.

Another way of doing this would be using a global list to store each element. Again, this isn't the most efficient or pythonic way:

l = []
def extract(a):
    #recursive algorithm for extracting items from a list of lists and items
    if type(a) is list:
        for item in a:
            extract(item)
    else:
        global l
        l.append(a)
Related