Python - Turn list of lists into a single list

1

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"]
    
asked by anonymous 09.09.2018 / 22:25

2 answers

1

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']

See it working on Ideone

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
    
09.09.2018 / 23:35
0

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.

    
09.09.2018 / 23:26