join list of lists in python


Question

Is the a short syntax for joining a list of lists into a single list( or iterator) in python?

For example I have a list as follows and I want to iterate over a,b and c.

x = [["a","b"], ["c"]]

The best I can come up with is as follows.

result = []
[ result.extend(el) for el in x] 

for el in result:
  print el
1
279
4/4/2009 4:00:35 AM

Accepted Answer

import itertools
a = [['a','b'], ['c']]
print(list(itertools.chain.from_iterable(a)))
410
7/17/2019 4:53:47 PM

If you're only going one level deep, a nested comprehension will also work:

>>> x = [["a","b"], ["c"]]
>>> [inner
...     for outer in x
...         for inner in outer]
['a', 'b', 'c']

On one line, that becomes:

>>> [j for i in x for j in i]
['a', 'b', 'c']

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon