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]
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With