1

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?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
ozzyzig
  • 709
  • 8
  • 19
  • possible duplicate of [Making a flat list out of list of lists in Python](http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) – martineau Oct 03 '13 at 22:27

3 Answers3

12
>>> 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]]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

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]]
Birei
  • 35,723
  • 2
  • 77
  • 82
0

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]]