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
  • 33,416
  • 13
  • 100
  • 127
ozzyzig
  • 669
  • 7
  • 18
  • 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

2 Answers2

11
>>> 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
  • 740,318
  • 145
  • 1,296
  • 1,325
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
  • 34,778
  • 2
  • 71
  • 80