Possible Duplicate:
Making a flat list out of list of lists in Python
In python 3
, how can I convert a list [['a'], ['b']]
to ['a','b']
?
I am a beginner programmer and have not been able to solve this problem myself.
Possible Duplicate:
Making a flat list out of list of lists in Python
In python 3
, how can I convert a list [['a'], ['b']]
to ['a','b']
?
I am a beginner programmer and have not been able to solve this problem myself.
Try this:
a = [['a'],['b']]
a = [item for list in a for item in list]
print a
>>>['a', 'b']
Try:
[i[0] for i in [['a'], ['b']]
>>> ['a','b']
Use itertools
, specifically itertools.chain
(this is much better than devising your own way of doing it):
>>> l = [['a'], ['b']]
>>> print(list(itertools.chain.from_iterable(l)))
['a', 'b']
This is faster than the pure list-comprehension solution as well:
$ 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)