How can I make a list of lists into a single list?
I need to turn this:
lista = [["Danilo","Gilson"],["Eduarda",["Costa","Otávio"]]]
in this:
lista = ["Danilo","Gilson","Eduarda","Costa","Otávio"]
How can I make a list of lists into a single list?
I need to turn this:
lista = [["Danilo","Gilson"],["Eduarda",["Costa","Otávio"]]]
in this:
lista = ["Danilo","Gilson","Eduarda","Costa","Otávio"]
Using recursion and list comprehension looks pretty short :
def lista_simples(lista):
if isinstance(lista, list):
return [sub_elem for elem in lista for sub_elem in lista_simples(elem)]
else:
return [lista]
lista = [["Danilo","Gilson"],["Eduarda",["Costa","Otávio"]]]
resultado = lista_simples(lista)
print(resultado) # ['Danilo', 'Gilson', 'Eduarda', 'Costa', 'Otávio']
For simplicity I just left the test with type list
. If you want the function to work for any iteravel you can switch to isinstance(lista, Iterable)
but you will have to disregard it when it is a string
which is also an iterable. In this case the ideal would be then:
if isinstance(lista, Iterable) and not isinstance(lista, str):
And adding import
to Iterable
from collections import Iterable
I tried to abstract for a function and one of the forms would be this:
def lista_unica(lista):
result = []
for item in lista:
if (isinstance(item, (list, tuple))):
result = lista.extend(item)
else:
result.append(item)
return result
>>> lista = [["Danilo","Gilson"],["Eduarda",["Costa","Otávio"]]]
>>> print(lista_unica(lista))
['Danilo', 'Gilson', 'Eduarda', 'Costa', 'Otávio']
Another way would be to use recursion that will only make calls to the append
method.