4

Possible Duplicate:
Flatten (an irregular) list of lists in Python

I have a list which consists of many lists. Here is an example,

[
    [Obj, Obj, Obj, Obj],
    [Obj],
    [Obj],
    [
        [Obj,Obj],
        [Obj,Obj,Obj]
    ]
]

Is there a way to join all these items together as one list, so the output will be something like

[Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj]
NickD
  • 5,088
  • 1
  • 18
  • 34
dotty
  • 38,389
  • 65
  • 144
  • 195
  • 3
    duplicate: http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python – Gary Kerr Jun 15 '10 at 14:43
  • duplicate: http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python – danben Jun 15 '10 at 14:49

2 Answers2

7

Yes, here's one way to do it:

def flatten(lst):
    for elem in lst:
        if type(elem) in (tuple, list):
            for i in flatten(elem):
                yield i
        else:
            yield elem

Please note, this creates a generator, so if you need a list, wrap it in list():

flattenedList = list(flatten(nestedList))
Skilldrick
  • 67,147
  • 33
  • 171
  • 227
1

Stolen from MonkeySage, here:

def iter_flatten(iterable):
  it = iter(iterable)
  for e in it:
    if isinstance(e, (list, tuple)):
      for f in iter_flatten(e):
        yield f
    else:
      yield e
Oddthinking
  • 22,854
  • 19
  • 79
  • 119