If some arrays isn't nested - then
def flatten(something):
if isinstance(something, (list, tuple, set, range)):
for sub in something:
yield from flatten(sub)
else:
yield something
test = flatten(ini_list)
list(test)
CodePudding user response:
You will need to check the type of each list item to determine if it is merely a value to output or a sublist to expand.
Using a list comprehension:
Input_List = [['a', 'b'],'c','d',['e', 'f']]
Final_List = [v for i in Input_List for v in (i if isinstance(i,list) else [i])]
print(Final_List)
['a', 'b', 'c', 'd', 'e', 'f']
Or using an iterative loop:
Final_List = []
for item in Input_List:
if isinstance(item,list): Final_List.extend(item)
else: Final_List.append(item)
print(Final_List)
['a', 'b', 'c', 'd', 'e', 'f']
Or using a recursive function if you need to flatten all levels of nested lists:
def flat(A):
return [v for i in A for v in flat(i)] if isinstance(A,list) else [A]
Input_List = [['a', 'b'],'c','d',['e2', 'f3',['x','y']]]
Final_List = flat(Input_List)
print(Final_List)
['a', 'b', 'c', 'd', 'e2', 'f3', 'x', 'y']