tags:

views:

120

answers:

3

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

Hay All.

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 1 list, so the output will be something like

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

Thanks

+1  A: 

There are loads and loads of answers on this page. HTH.

Deniz Dogan
+4  A: 

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
+1  A: 

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