-2

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']
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
CodeMaster
  • 431
  • 4
  • 14

2 Answers2

2

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']
Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

this working only for -> multdimensional at the same dimension

from itertools import chain
 
ini_list = [[1, 2, 3],
            [3, 6, 7],
            [7, 5, 4]]
             
print ("initial list ", str(ini_list))
 
flatten_list = list(chain.from_iterable(ini_list))
 
print ("final_result", str(flatten_list))

enter image description here


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)

            
Piotr Żak
  • 2,046
  • 5
  • 18
  • 30