Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join a list of lists together into one list in Python [duplicate]

Tags:

python

list

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]
like image 836
dotty Avatar asked Feb 27 '23 20:02

dotty


1 Answers

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))
like image 128
Skilldrick Avatar answered Mar 22 '23 23:03

Skilldrick