1

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"]
Jason
  • 313
  • 2
  • 8
  • Does this answer your question? [How do I make a flat list out of a list of lists?](https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-a-list-of-lists) – Ryan Fu Jun 23 '22 at 21:42

1 Answers1

1

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)
Ryan Fu
  • 349
  • 1
  • 5
  • 22