How can I flatten a list of lists into a list?
For ex,:
Input_List = [['a', 'b'],'c','d',['e', 'f']]
Expectation:
Final_List = ['a','b','c','d','e','f']
How can I flatten a list of lists into a list?
For ex,:
Input_List = [['a', 'b'],'c','d',['e', 'f']]
Expectation:
Final_List = ['a','b','c','d','e','f']
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']