How to unnest a nested list

Python

Python Problem Overview


> Possible Duplicate:
> Making a flat list out of list of lists in Python

I am trying to find an easy way to turn a multi dimensional (nested) python list into a single list, that contains all the elements of sub lists.

For example:

A = [[1,2,3,4,5]]

turns to

A = [1,2,3,4,5]

or

A = [[1,2], [3,4]]

turns to

A = [1,2,3,4]

Python Solutions


Solution 1 - Python

Use itertools.chain:

> itertools.chain(*iterables): > > Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

Example:

from itertools import chain

A = [[1,2], [3,4]]

print list(chain(*A))
# or better: (available since Python 2.6)
print list(chain.from_iterable(A))

The output is:

[1, 2, 3, 4]
[1, 2, 3, 4]

Solution 2 - Python

Use reduce function

reduce(lambda x, y: x + y, A, [])

Or sum

sum(A, [])

Solution 3 - Python

the first case can also be easily done as:

A=A[0]

Solution 4 - Python

itertools provides the chain function for that:

From http://docs.python.org/library/itertools.html#recipes:

def flatten(listOfLists):
    "Flatten one level of nesting"
    return chain.from_iterable(listOfLists)

Note that the result is an iterable, so you may need list(flatten(...)).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncodiousView Question on Stackoverflow
Solution 1 - PythonmoooeeeepView Answer on Stackoverflow
Solution 2 - PythonlolloView Answer on Stackoverflow
Solution 3 - PythoncodiousView Answer on Stackoverflow
Solution 4 - Pythonnd.View Answer on Stackoverflow