how to create a list from multiple sublists

Viewed 32

I have a list with the following structure:

list = ['a', ['b','c','d'], ['e','f']]

how can I create the following structure from it:

list = ['a','b','c','d','e','f']
2 Answers
list = ['a', ['b','c','d'], ['e','f']]
lst = [element for nested_list in list for element in nested_list]
print(lst)

Result:

['a', 'b', 'c', 'd', 'e', 'f']

This supports nested list too.

res = []
def parse(li):
    if isinstance(li, list):
        for a in li:
            parse(a)
        return
    res.append(li)
my_List = ['a', ['b','c','d', ['g', 'h']], ['e','f']]
parse(my_List)
print(res)

Output:

['a', 'b', 'c', 'd', 'g', 'h', 'e', 'f']
Related