Convert a list of lists into a single list

8

I'm working on Python 2.7. I have this result:

Resultado=[['A','B','C'],['D','E','F'],['G','H','I']]

How can I make this a list? And get the following:

Lista=['A','B','C','D','E','F','G','H','I']

Thank you!

    
asked by anonymous 30.05.2016 / 16:50

2 answers

6

To make a single list of:

Resultado=[['A','B','C'],['D','E','F'],['G','H','I']]

Make (excuse to import external libs for this, this is what I recommend):

Lista = [item for sublista in Resultado for item in sublista]

Alternatives:

Lista = []
for i in Resultado:
    Lista.extend(i)

print Lista  #['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']

Or:

Lista = []
[Lista.extend(i) for i in Resultado]

print Lista  #['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
    
30.05.2016 / 16:54
4

I would do this using the method chain of itertools

from itertools import chain

Resultado  = [['A','B','C'],['D','E','F'],['G','H','I']]

Lista = list(chain(*Resultado))

print (Lista); # ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']

Just to get more information on how to search if necessary, the name of this operation in English is called flatten . It means you're transforming a multilevel list into a one-dimensional list.

    
30.05.2016 / 17:18