-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
  • 151,199
  • 17
  • 111
  • 216
CodeMaster
  • 315
  • 2
  • 9
  • 2
    Please take the [tour], read [what's on-topic here](/help/on-topic), [ask], and the [question checklist](//meta.stackoverflow.com/q/260648/843953), and provide a [mre]. "Implement this feature for me" is off-topic for this site because SO isn't a free online coding service. You have to _make an honest attempt_, and then ask a _specific question_ about your algorithm or technique. – Pranav Hosangadi Oct 05 '21 at 16:55
  • 2
    [How much research effort is expected of Stack Overflow users?](//meta.stackoverflow.com/a/261593/843953) – Pranav Hosangadi Oct 05 '21 at 16:55
  • 1
    Please check your code for typos! – Klaus D. Oct 05 '21 at 16:55
  • The input shown is not a list of lists. You have lists **and scalars** – OneCricketeer Oct 05 '21 at 16:57

2 Answers2

1

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
  • 1,680
  • 2
  • 12
  • 28
1

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.
  • 34,859
  • 4
  • 30
  • 47