Convert list [['a'], ['b']] to ['a', 'b']

Possible duplicate:
Creating a flat list from a list of lists in Python

In python 3 , how to convert the list [['a'], ['b']] to ['a','b'] ?

I am a beginner programmer and myself could not solve this problem.

+4
source share
3 answers

Try the following:

 a = [['a'],['b']] a = [item for list in a for item in list] print a >>>['a', 'b'] 
+3
source

Try:

 [i[0] for i in [['a'], ['b']] >>> ['a','b'] 
+2
source

Use itertools , in particular itertools.chain (this is much better than developing your own way of doing this):

 >>> l = [['a'], ['b']] >>> print(list(itertools.chain.from_iterable(l))) ['a', 'b'] 

This is faster than a clean list solution:

 $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]' 10000 loops, best of 3: 53.9 usec per loop $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'list(itertools.chain.from_iterable(l))' 10000 loops, best of 3: 29.5 usec per loop 

(Tests adapted from this question)

+2
source

All Articles