0

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']
kaan46
  • 83
  • 6
  • 3
    What you seem to be looking for is "flattening" the list. Possible duplicate of https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-a-list-of-lists – Wouter De Coster Sep 06 '22 at 11:02
  • Don't use `list` as variable name, you're shadowing the builtin class. Sooner or later you'll need to do `list(...)` and end up scratching your head with a `'list' object is not callable` error. – fsimonjetz Sep 06 '22 at 11:18

2 Answers2

1
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']
Turan
  • 104
  • 9
  • This does not generally work, only in this special case because the non-list item happens to be a string (iterable) with only one character. E.g., if the first element was `'xy'` it would give a presumably unexpected result and if it was integers, it would throw an error. – fsimonjetz Sep 06 '22 at 11:13
  • On a side note, don't use builtin names like `list` as variable names. – fsimonjetz Sep 06 '22 at 11:13
0

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']
Ali-Ibrahim
  • 835
  • 1
  • 6
  • 16