0

there is an exercise I was assigned to solve a week ago and I can't seem to find a solution to it. I want to create a Python function which receives a list and returns every element inside the list in a new one (even if there are nested elements inside it).

def ListOfLists(lista):
    listaUnica = []
    if(type(lista) != list):
        return None
    for i in lista:
        if (type(i) != list):
            listaUnica.append(i)
        elif(type(i) == list):
            for elemento in i:
                if(type(elemento) == list):
                    listaUnica.append(elemento)
                    continue
                elif(type(elemento) != list):
                    listaUnica.append(elemento)
    return listaUnica

This is the best function I came up with. The problem that I have with this function is that it doesn't analyse while looping though the list if an element is indeed a list, if it turns out true, loop through that nested list and so on until there are no more nested lists. While doing so I want it to return the elements in the same order that they were assigned originally.

Let's suppose:

lista = [1,2,[3, [4, 5, [6]], 7]
ListOfLists(lista)

Expected output:

[1, 2, 3, 4, 5, 6, 7]

Or another example:

lista = [1,2,['a','b'],[10]]
ListOfLists(lista)

Expected output:

[1, 2, 'a', 'b', 10]

I'm not allowed to use any framework or library.

petezurich
  • 9,280
  • 9
  • 43
  • 57
  • You'll need a recursive function... – AKX Oct 02 '22 at 19:07
  • 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) – Stuart Oct 02 '22 at 19:13
  • 1
    Or probably a closer duplicate: https://stackoverflow.com/questions/2158395 – Stuart Oct 02 '22 at 19:14
  • @Stuart it should be a duplicate of the second one, yes. I am out of close votes for today, or I would hammer it. – Karl Knechtel Oct 02 '22 at 19:47

2 Answers2

2

You'll need a recursive function (a function that calls itself) to walk through any depth of nested lists.

If you're allowed (and know how) to write a generator function,

def flatten_lists(lista):
    for item in lista:
        if isinstance(item, list):
            yield from flatten_lists(item)
        else:
            yield item


lista = [1, 2, [3, [4, 5, [6]], 7]]
print(list(flatten_lists(lista)))

does the trick quite elegantly.

Without using generators, you'd do

def flatten_lists(lista):
    output = []
    for item in lista:
        if isinstance(item, list):
            output.extend(flatten_lists(item))
        else:
            output.append(item)
    return output

To emulate the recursion by hand (i.e. without a real recursive function), you could do

def flatten_lists(lista):
    queue = [lista]
    output = []
    while queue:
        item = queue.pop(0)
        if isinstance(item, list):
            queue = item + queue
        else:
            output.append(item)
    return output
AKX
  • 152,115
  • 15
  • 115
  • 172
0

Recursive method

def flatten(list_of_lists):
    if len(list_of_lists) == 0:
        return list_of_lists
    if isinstance(list_of_lists[0], list):
        return flatten(list_of_lists[0]) + flatten(list_of_lists[1:])
    return list_of_lists[:1] + flatten(list_of_lists[1:])


print(flatten([[1, 2, 3, 4], [5, 6, 7], [8, 9, [10]], 11]))
Vitaliy Korolyk
  • 182
  • 2
  • 6