4

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.

Community
  • 1
  • 1

3 Answers3

3

Try this:

a = [['a'],['b']]

a = [item for list in a for item in list]
print a
>>>['a', 'b']
2

Try:

[i[0] for i in [['a'], ['b']]
>>> ['a','b']
alexvassel
  • 10,600
  • 2
  • 29
  • 31
2

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)

Community
  • 1
  • 1
arshajii
  • 127,459
  • 24
  • 238
  • 287