18
votes

Duplicates:

Lets say I have a list with nested lists:

[["a","b","c"], ["d","e","f"], ["g","h","i","j"]...]

what is the best way to convert it to a single list like that

["a", "b", "c", "d", "e"....]
3
While this is probably a duplicate of something, it's not a duplicate of the linked question, which is about creating a list like [["a", "d", "g"], ["a", "d", "h"], ["a", "d", "i"], ...] which is not at all what is wanted here. - agf
@agf replaced possible duplicates with actual duplicates - dbr

3 Answers

33
votes

Use itertools.chain:

from itertools import chain

list(chain.from_iterable(list_of_lists))
20
votes

There's a straight forward example of this in the itertools documentation (see http://docs.python.org/library/itertools.html#recipes look for flatten()), but it's as simple as:

>>> from itertools import chain
>>> list(chain(*x))
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Or, it can be done very easily in a single list comprehension:

>>> x=[["a","b","c"], ["d","e","f"], ["g","h","i","j"]]
>>> [j for i in x for j in i]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Or via reduce():

>>> from operator import add
>>> reduce(add, x)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
3
votes

An alternative solution to using itertools.chain would be:

>>> li = [["a","b","c"], ["d","e","f"], ["g","h","i","j"]]
>>> chained = []
>>> while li:
...     chained.extend(li.pop(0))
... 
>>> chained
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

EDIT: The above example will consume your original lists while building the new one, so it should be an advantage if you are manipulating very large lists and want to minimise memory usage. If this is not the case, I would consider using itertools.chain more pythonic way to achieve the result.