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.