Un-nesting nested lists

Question:

Hi I was wondering how I could un-nest a nested nested list. I have:

list = [[[1,2,3]], [[4,5,6]], [[7,8,9]]]

I would like to to look as follows:

new_list = [[1,2,3], [4,5,6], [7,8,9]]

How to do it?

Asked By: ozzyzig

||

Answers:

>>> L = [[[1,2,3]], [[4,5,6]], [[7,8,9]]]
>>> [x[0] for x in L]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

For multiple nestings:

def unnesting(l):
    _l = []
    for e in l:
        while isinstance(e[0], list):
            e = e[0]
        _l.append(e)
    return _l

A test:

In [24]: l = [[[1,2,3]], [[[[4,5,6]]]], [[[7,8,9]]]]
In [25]: unnesting(l)
Out[25]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Answered By: Birei

I found another solution that might be easier and quicker here and also mentioned here.

from itertools import chain

nested_list = [[[1,2,3]], [[4,5,6]], [[7,8,9]]]
my_unnested_list = list(chain(*nested_list))
print(my_unnested_list)

which results in your desired output as:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Answered By: Javid Jouzdani
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.