python – How to unnest a nested list

python – How to unnest a nested list

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]

Use reduce function

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

Or sum

sum(A, [])

python – How to unnest a nested list

the first case can also be easily done as:

A=A[0]

Leave a Reply

Your email address will not be published.